Fetching Image Data
Explore how to implement image data fetching in React Native apps using XState. Learn to model asynchronous fetch operations as state machines, handle loading, success, and failure states, invoke real endpoints, and manage data flow between nested machines.
Fetching data isn’t always the strong suit of state management libraries. After all, it’s not their basic responsibility. In the case of XState, however, fetching comes very naturally, as every Promise can be modeled as a state machine. At a high level, we need to kick off a function that will be in a default loading state. We’ll wait for something to happen with it—either resolve or reject—and go to the appropriate resolved or rejected states.
Image-fetching machine
Here’s how our image-fetching machine is shaping up:
What we can see here is a very simple machine prepared to describe the process of fetching data from an external source. We have three states:
The initial state of
loadingon line 20.The
successstate on line 26.The
failurestates on line 29.
We can see two actions in the loading state on lines 22–23, which could be used to manage the fetching mechanism. ...