Skip to content

Instantly share code, notes, and snippets.

@bmingles
Last active January 9, 2022 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmingles/3ba3a07b5613002eb79eceb6aa1954df to your computer and use it in GitHub Desktop.
Save bmingles/3ba3a07b5613002eb79eceb6aa1954df to your computer and use it in GitHub Desktop.
Example of using Mobx + React
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)
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