Loading Data from the Server

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 5 years ago

Let's stop hardcoding our initial state and fetch it from the server instead.

In this lesson you will learn:

  • Set up basic data fetching
  • Leverage the afterCreate lifecycle hook to automatically run any setup logic a model instance needs to do after creation

Instructor: [00:00] 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.

[00:11] 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.

[00:24] 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.

[00:43] 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.

[01:01] 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.

[01:17] 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.

[01:32] 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.

[01:52] 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.

[02:10] 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.

[02:21] 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.

[02:48] Our application now fetches data from the server. It does so automatically by using the afterCreate life cycle hook.