mobx-react-use-autorun
v4.0.49
Published
Provide concise usage for mobx in react
Downloads
581
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
- A JavaScript library for building user interfaces (https://react.dev)
- Reactive Extensions Library for JavaScript (https://www.npmjs.com/package/rxjs)
- 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
- From https://code.visualstudio.com install Visual Studio Code.
- 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.