...

/

Using XState for the FavoritedImages Surface

Using XState for the FavoritedImages Surface

Learn about incorporating and integrating XState machines for tasks and implementing a basic state machine.

So far, we have set up a basic machine that could be used to control the user flow in the app. Let’s add a new machine for our real-world use case: liking images in a social media clone app.

Minimum viable product

We’ll start by creating a machine minimum viable product (MVP):

Press + to interact
// src/machines/likeImagesMachine.js
import { createMachine } from "xstate";
/**
* XState machine for managing liked images.
*/
export const likeImagesMachine = createMachine({
id: "likeImagesMachine",
// Context contains the likedImages array
context: {
likedImages: [
{ /* Example Image Object 1 */ },
{ /* Example Image Object 2 */ },
// ... more image objects
],
},
// Initial state when the machine is created
initial: "loading",
// States of the machine
states: {
loading: {}, // State for loading initial data
ready: {}, // State when the machine is ready
error: {}, // State for handling errors
},
});

Let’s analyze this code from the top:

  • Line 3: We start by importing the createMachine function, which we use on the very first line of the likeImagesMachine function on line 9.

  • Lines 13–18: We set the ID of the machine and the context of the machine. Bear in mind that XState context is different from React context. We’ve talked a lot about ReactJS context; we know it can be used to share state between components. XState context is a container for ...