Instructor: So far, all of our state has been hard-coded in our application, so it's time to integrate with the back ends. For that, we are going to reuse our JSON server again.
We should, of course, populate it with some data. Here's a simple trick to make our store accessible from our devtools, from the browser console. We just assign it to some global variable.
The convenient little thing about that is that we can now access our state from here. You can even say, "Give me the JSON of the current state," which is basically the same as calling, "Get snapshot." Here is all our current states.
Let's simply stringify that and put it in our database, so there it is, our initial states. We even have all the inaudible . Homer actually has a wish list.
Here's our data, so let's make sure it gets loaded automatically. Just drop our initial state. Now, there are no users in the application, and we can introduce the logic to load all the data.
We are going to introduce an additional action, and it is an asynchronous flow again. We're going to load it with the node-fetch again. We're going to apply the JSON we receive to the users' map.
To do that, we use a built-in function of Mobx-state-tree, which is called applySnapshot, and applySnapshot is a very nifty feature. It compares the state it already has with the state it receives. It tries to update with as few changes as possible.
When the application starts up, we can simply call, load the group. That should start fetching our data, and here we have it. We have back our state, including our wish list and all our recipients after all, so the references were also appropriately de-serialized.
Maybe this is something that should happen always, this loading the data when the group is created. In that case, you can use life cycle hooks.
Now, we don't load anything, but we can define several actions with which has predetermined names, which has special meaning to MobX-state-tree. There's a special action, and it's called afterCreate. This is always called whenever an instance is created and the entire object is set up. After the case, we could simply call self.load.
Our application now fetches data from the server. It does so automatically by using the afterCreate life cycle hook.