4 May 2018 0 comments React, JavaScript
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...
App
component and created a new sub-component (that App
renders) called 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));
.Item
component also be an observer and not just the TodoList
component. store
and, in this version, is an instance of the TodoStore
class. The intention is to make store
be an instance of combined different store classes, with TodoStore
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...
react-router
to the mix so opening the Todo list is just one of many possible views. 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. window
. That means I can open the web console and type store.items[2].text = "Test change"
and simply by hitting enter the app re-renders to this change.