This is not meant as a tutorial on MobX but hopefully it can be inspirational for people who have grokked how React's setState
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:
https://github.com/peterbe/workon/commit/c1846ce782ce7c9da16f44b10c48f0be1337ae41
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...
- As part of this change, I moved the logic from the
App
component and created a new sub-component (thatApp
renders) calledTodoList
. This was not necessary to add MobX. - There are a bunch of little unrelated edits in that such as deleting some commented out code.
store.items.sort((a, b) => b.id - a.id);
doesn't actually work. You're supposed to dostore.items.replace(store.items.sort((a, b) => b.id - a.id));
.- Later I made the
Item
component also be an observer and not just theTodoList
component. - The exported store is called
store
and, in this version, is an instance of theTodoStore
class. The intention is to makestore
be an instance of combined different store classes, withTodoStore
being 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 console.log
debugging.
However, the intention is to...
- Add
react-router
to the mix so opening the Todo list is just one of many possible views. - Now the
Store.js
file 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. - Note that the store is also put into
window
. That means I can open the web console and typestore.items[2].text = "Test change"
and simply by hitting enter the app re-renders to this change.
Comments