Fetching Data

Learn how to fetch asynchronous data and optimizing with generator functions in MobX-State-Tree.

We have our image list stored on the server. MobX-State-Tree proposes two ways of fetching asynchronous data, but both are actions.

Creating an action

Let’s create an action in the store:

Press + to interact
// Importing necessary modules from MobX state tree and store
import { types } from "mobx-state-tree";
import { LikedImages } from "./models/LikedImages";
import { User } from './models/User';
// RootStore model definition
const RootStore = types
.model({
users: User,
likedImages: LikedImages,
})
.actions(self => ({
// Async action to fetch images data
async fetchImages() {
// Making an asynchronous API call to fetch liked images data
const response = await fetch(requestBase + "/john_doe/likedImages.json");
// Parsing the JSON response
const data = await response.json();
// Returning the fetched data
return data;
}
}));

We need an asynchronous function that will do the fetching—we have called it fetchImages on lines 14–22 above. This function uses JavaScript’s fetch function on line 16 and returns data from the server on line 22.

Passing data into the model

Now that we have the data, we need to pass it to the LikedImages model. Let’s add a function that will do just that:

Press + to interact
// Continuing from the previous RootStore definition
// Adding actions to the RootStore model
const RootStore = types
.model({
users: User,
likedImages: LikedImages,
})
.actions(self => ({
// Action to set new liked images
setLikedImages(newImages) {
// Replacing the existing image list with the new one
store.likedImages.imageList.replace(newImages);
},
// Async action to fetch liked images data
async fetchImages() {
// Making an asynchronous API call to fetch liked images data
const response = await fetch(requestBase + "/john_doe/likedImages.json");
// Parsing the JSON response
const data = await response.json();
// Updating the store with the fetched images
store.setLikedImages(data);
}
}));

Here’s an explanation of the above code:

    ...