Using XState for the FavoritedImages Surface
Learn about incorporating and integrating XState machines for tasks and implementing a basic state machine.
We'll cover the following...
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):
// src/machines/likeImagesMachine.jsimport { createMachine } from "xstate";/*** XState machine for managing liked images.*/export const likeImagesMachine = createMachine({id: "likeImagesMachine",// Context contains the likedImages arraycontext: {likedImages: [{ /* Example Image Object 1 */ },{ /* Example Image Object 2 */ },// ... more image objects],},// Initial state when the machine is createdinitial: "loading",// States of the machinestates: {loading: {}, // State for loading initial dataready: {}, // State when the machine is readyerror: {}, // 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 thelikeImagesMachine
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 ...