This is not meant as a tutorial on MobX but hopefully it can be inspirational for people who have grokked how React's
works but now feel they need to move the state management in their React app out of the components.
To jump right in, here is a changeset that demonstrates how to replace
setState with a MobX store:
It's a really simple Todo list application based on create-react-app. Not much to read into at this point.
Here are some caveats to be aware if you look at the diff and wonder...
Appcomponent and created a new sub-component (that
TodoList. This was not necessary to add MobX.
store.items.sort((a, b) => b.id - a.id);doesn't actually work. You're supposed to do
store.items.replace(store.items.sort((a, b) => b.id - a.id));.
Itemcomponent also be an observer and not just the
storeand, in this version, is an instance of the
TodoStoreclass. The intention is to make
storebe an instance of combined different store classes, with
TodoStorebeing just one of them.
Caveat last but not least...
This diff does not much other than adding more library dependencies and fancy "observable arrays" that are hard to introspect with
However, the intention is to...
react-routerto the mix so opening the Todo list is just one of many possible views.
Store.jsfile can be all about data. Data retrieval, storage, manipulation, mutation etc. The other components will be more simple since their only job is to render that's in the store and send events back to the store based on user actions.
window. That means I can open the web console and type
store.items.text = "Test change"and simply by hitting enter the app re-renders to this change.