Fetching Data
Explore how to fetch asynchronous image data in a React Native app using MobX-State-Tree. Learn to create actions for fetching, update models with server data, and leverage life cycle hooks and generator functions to optimize state management and improve data handling in your application.
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:
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:
Here’s an explanation of the above code: