Last active
January 9, 2022 23:44
-
-
Save bmingles/3ba3a07b5613002eb79eceb6aa1954df to your computer and use it in GitHub Desktop.
Example of using Mobx + React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { observer } from 'mobx-react-lite' | |
const MyComponent: React.FC = () => { | |
// I would typically get this from context API with custom hook instead of local useMemo | |
// e.g. const { name, age, loadAge, loadName } = useSomeService() | |
const { age, name, loadAge, loadName } = React.useMemo(() => new SomeService(), []) | |
React.useEffect(() => { | |
loadAge() | |
void loadName() | |
}, [loadName]) | |
// Any changes to `name` or `age` in the service will cause React to re-render | |
// this component. Mobx handles the subscription to the `name` and `age` | |
// observables, but you just treat it like it is a string prop | |
return ( | |
<div> | |
{name} {age} | |
</div> | |
) | |
} | |
// This is what makes the component subscribe to mobx observables | |
export default observer(MyComponent) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeAutoObservable, runInAction } from 'mobx' | |
import { fetchName } from './api' | |
class SomeService { | |
constructor() { | |
// This makes methods actions and properties observable | |
makeAutoObservable(this) | |
} | |
age = 0 | |
// synchronous action | |
loadAge = () => { | |
this.age = 4 | |
} | |
name = '' | |
// async action | |
loadName = async () => { | |
const name = await fetchName() | |
// This is the one mobx API thing you have to use with async to tell the | |
// framework something is changing. You don't have to use it for change | |
// in syncrhonous methods | |
runInAction(() => { | |
this.name = name | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment