npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mobx-react-use-autorun

v4.0.49

Published

Provide concise usage for mobx in react

Downloads

635

Readme

Provide concise usage for mobx in react

Installation

npm install mobx-react-use-autorun

Usage

Define state with useMobxState

import { observer, useMobxState } from 'mobx-react-use-autorun';

export default observer(() => {

    const state = useMobxState({
        age: 16
    });

    return <div
        onClick={() => state.age++}
    >
        {`John's age is ${state.age}`}
    </div>
})

More example - Form validation:

import { Button, TextField } from '@mui/material';
import { observer, useMobxState } from 'mobx-react-use-autorun';

export default observer(() => {

    const state = useMobxState({
        name: "",
        submit: false,
        errors: {
            name() {
                return state.submit &&
                    !state.name &&
                    "Please fill in the username";
            },
            hasError() {
                return Object.keys(state.errors)
                    .filter(s => s !== "hasError")
                    .some(s => (state.errors as any)[s]());
            }
        }
    });

    async function ok(){
        state.submit = true;
        if (state.errors.hasError()) {
            console.log("Submission Failed");
        } else {
            console.log("Submitted successfully");
        }
    }

    return (<div className='flex flex-col' style={{ padding: "2em" }}>
        <TextField
            value={state.name}
            label="Username"
            onChange={(e) => state.name = e.target.value}
            error={!!state.errors.name()}
            helperText={state.errors.name()}
        />
        <Button
            variant="contained"
            style={{ marginTop: "2em" }}
            onClick={ok}
        >Submit</Button>
    </div>)
})

More example - Use props and other hooks:

import { observer, useMobxState } from 'mobx-react-use-autorun';
import { useRef } from 'react';


export default observer((props: { user: { name: string, age: number } }) => {

    const state = useMobxState({
    }, {
      containerRef: useRef<HTMLDivElement>(null),
      ...props,
    });

    return <div
      ref={state.containerRef}
      onClick={() => {
        props.user.age++;
      }}
    >
        {`${props.user.name}'s age is ${props.user.age}.`}
    </div>

})

Lifecycle hook with useMount

useMount is a lifecycle hook that calls a function after the component is mounted. It provides a subscription as parameter, which will be unsubscribed when the component will unmount.

It support Strict Mode. Strict Mode: In the future, React will provide a feature that lets components preserve state between unmounts. To prepare for it, React 18 introduces a new development-only check to Strict Mode. React will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount. If this breaks your app, consider removing Strict Mode until you can fix the components to be resilient to remounting with existing state.

import { Subscription } from 'rxjs'
import { observer, useMount } from 'mobx-react-use-autorun'

export default observer(() => {

    useMount((subscription) => {
        console.log('component is loaded')

        subscription.add(new Subscription(() => {
            console.log("component will unmount")
        }))
    })

    return null;
})

Subscription property changes with useMobxEffect

import { useMobxState, observer } from 'mobx-react-use-autorun';
import { useMobxEffect, toJS } from 'mobx-react-use-autorun'

export default observer(() => {

    const state = useMobxState({
        randomNumber: 1
    });

    useMobxEffect(() => {
        console.log(toJS(state))
    }, [state.randomNumber])

    return <div onClick={() => state.randomNumber = Math.random()}>
        {state.randomNumber}
    </div>
})

Define global mutable data with observable

// File: GlobalState.tsx
import { observable } from 'mobx-react-use-autorun';

export const globalState = observable({
    age: 15,
    name: 'tom'
});

// File: UserComponent.tsx
import { observer } from "mobx-react-use-autorun";
import { globalState } from "./GlobalState";

export default observer(() => {
    return <div
        onClick={() => {
            globalState.age++;
        }}
    >
        {`${globalState.name}'s age is ${globalState.age}.`}
    </div>;
})

Get the real data of the proxy object with toJS

"toJS" will cause the component to re-render when data changes. Please do not execute "toJS(state)" in component rendering code, it may cause repeated rendering. Wrong Example:

import { toJS, observer, useMobxState } from 'mobx-react-use-autorun'
import { v1 } from 'uuid'

export default observer(() => {

    const state = useMobxState({}, {
        id: v1()
    })

    toJS(state)

    return null;
})

Other than that, all usages are correct. Correct Example:

import { toJS, useMobxEffect } from 'mobx-react-use-autorun';
import { observer, useMobxState } from 'mobx-react-use-autorun';
import { v1 } from 'uuid'

export default observer(() => {

    const state = useMobxState({
        name: v1()
    });

    useMobxEffect(() => {
        console.log(toJS(state));
        console.log(toJS(state.name));
    })

    console.log(toJS(state.name));

    return <button
      onClick={() => {
        console.log(toJS(state));
        console.log(toJS(state.name));
      }}
    >
      {'Click Me'}
    </button>;
})

Notes - Work with non-observer components

Non-observer components cannot trigger re-rendering when the following data changes, please use "toJS" to do it.

  • array
  • object
  • The all data used in the new render callback
import { observer, toJS, useMobxState } from "mobx-react-use-autorun";
import { v1 } from "uuid";
import { Virtuoso } from 'react-virtuoso'

export default observer(() => {

  const state = useMobxState({
    userList: [{ id: 1, username: 'Tom' }]
  })

  toJS(state.userList)

  return <Virtuoso
    style={{ width: "500px", height: "200px" }}
    data={state.userList}
    itemContent={(index, item) =>
      <div key={item.id} onClick={() => item.username = v1()}>
        {item.username}
      </div>
    }
  />
})

Notes - Work with typedjson

Typedjson is a strongly typed reflection library.

import { makeAutoObservable, toJS } from "mobx-react-use-autorun";
import { TypedJSON, jsonMember, jsonObject } from "typedjson";

@jsonObject
export class UserModel {

  @jsonMember(String)
  username!: string;

  @jsonMember(Date)
  createDate!: Date;

  constructor() {
    makeAutoObservable(this);
  }
}

const user = new TypedJSON(UserModel).parse(`{"username":"tom","createDate":"2023-04-13T04:21:59.262Z"}`);
console.log(toJS(user));

const anotherUser = new TypedJSON(UserModel).parse({
  username: "tom",
  createDate: "2023-04-13T04:21:59.262Z"
});
console.log(toJS(anotherUser));

Learn More

  1. A JavaScript library for building user interfaces (https://react.dev)
  2. Reactive Extensions Library for JavaScript (https://www.npmjs.com/package/rxjs)
  3. Material UI is a library of React UI components that implements Google's Material Design (https://mui.com)

Getting Started

This project was bootstrapped with Create React App. If you have any questions, please contact [email protected].

Development environment setup

  1. From https://code.visualstudio.com install Visual Studio Code.
  2. From https://nodejs.org install nodejs v22.

Available Scripts

In the project directory, you can run:

npm test

Run all unit tests.

npm run build

Builds the files for production to the dist folder.

npm run make

Publish to npm repository

Pre-step, please run

npm login --registry https://registry.npmjs.org

License

This project is licensed under the terms of the MIT license.