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 storeimport { types } from "mobx-state-tree";import { LikedImages } from "./models/LikedImages";import { User } from './models/User';// RootStore model definitionconst RootStore = types.model({users: User,likedImages: LikedImages,}).actions(self => ({// Async action to fetch images dataasync fetchImages() {// Making an asynchronous API call to fetch liked images dataconst response = await fetch(requestBase + "/john_doe/likedImages.json");// Parsing the JSON responseconst data = await response.json();// Returning the fetched datareturn 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 modelconst RootStore = types.model({users: User,likedImages: LikedImages,}).actions(self => ({// Action to set new liked imagessetLikedImages(newImages) {// Replacing the existing image list with the new onestore.likedImages.imageList.replace(newImages);},// Async action to fetch liked images dataasync fetchImages() {// Making an asynchronous API call to fetch liked images dataconst response = await fetch(requestBase + "/john_doe/likedImages.json");// Parsing the JSON responseconst data = await response.json();// Updating the store with the fetched imagesstore.setLikedImages(data);}}));
Here’s an explanation of the above code: