You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
3 Hrs
35 Min
27 Seg

Declarar la maquina de estados

5/15
Resources

How to start a project with Create React App?

Starting a project in React is exciting and follows an orderly process. We are going to use Create React App, one of the most popular tools to create the basis of a new project in React. To get started, follow these basic steps:

  1. Start your project with Create React App using the command:

    npx create-react-app ReactStateMachine

    Remember to change ReactStateMachine to the name you want for your project.

  2. After installation, you must move to the created directory to start working on it. Use:

    cd ReactStateMachine
  3. Before continuing, to keep the work area clean, you can use:

    clear

Now that you have your React project configured with Create React App, you are ready for the next step: installing the necessary dependencies.

How to configure XState in React?

XState is a powerful library for handling finite state machines that you can easily integrate into a React project. Here's how to do it:

  1. First, you need to install XState via npm:

    npm install xstate
  2. Then, install the XState integration package with React:

    npm install @xstate/react
  3. Once installed, start the server to start working on the project:

    npm start

When starting the server, make sure everything is working properly. Then, we will be able to create our first state machine.

How to create and configure a state machine in XState?

To use XState effectively, you must create and configure a state machine. Here we guide you through the process:

  1. Open your project in your favorite text editor (for example, Visual Studio Code) and navigate to the src folder.

  2. Create a new directory called Machines to better organize your machines code:

    /src/Machines
  3. Inside this folder, create a BookingMachine.js file. This file will store your state machine object.

  4. In BookingMachine.js, paste the configuration you designed in XState Visualizer:

    export default const bookingMachine = { id: 'booking', initial: 'initial', states: { initial: { /* configuration */ }, // Other states here }, };

This initial configuration of the state machine establishes its structure and states. Now, we can proceed to use it in our component.

How to integrate the state machine in a React component?

Integrating the state machine with React involves using hooks to manage its operation. Follow these steps:

  1. Create a Components folder in the root of src and inside it, a BaseLayout.js file:

    /src/Components/BaseLayout.js
  2. Define the BaseLayout component and use the useMachine hook from @xstate/react to initialize the machine:

    import React from 'react';import { useMachine } from '@xstate/react';import bookingMachine from '../Machines/BookingMachine';
    const BaseLayout = () => { const [state, send] = useMachine(bookingMachine);
     console.log(state);
     return <div>Hello</div>;};
    export default default BaseLayout;
  3. Don't forget to import your BaseLayout component into App.js:

    import React from 'react';import BaseLayout from './Components/BaseLayout';
    function App() { return ( < <div className="App"> <BaseLayout/> </div> );}
    export default default App;

By performing these steps, you will have successfully integrated a state machine into your React application. When you open the browser console, you'll be able to observe the initial state and its transitions in real time - it's just the beginning of how states can improve flow control in your applications!

Continue to explore the power of XState, and feel free to experiment with integrations and transitions that you can learn about in upcoming lessons. Practice and experimentation are key to mastering any technology - take heart and keep going!

Contributions 10

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

npx create-react-app react-state-machines
npm install xstate @xstate/react
.
src/Machines/bookingMachine.js:

import { createMachine } from 'xstate';

const bookingMachine = createMachine({
  id: 'buy plane tickets',
  initial: 'initial',
  states: {
    initial: {
      on: {
        START: 'search'
      }
    },
    search: {
      on: {
        CONTIUNE: 'passengers',
        CANCEL: 'initial'
      }
    },
    passengers: {
      on: {
        DONE: 'tickets',
        CANCEL: 'initial'
      }
    },
    tickets: {
      on: {
        FINISH: 'initial'
      }
    },
  }
})

export default bookingMachine

src/Components/BaseLayout.js:

import React from 'react';
import { useMachine } from '@xstate/react';
import bookingMachine from '../Machines/bookingMachine';

export const BaseLayout = ()=> {
    const [state,send] = useMachine(bookingMachine)

    console.log('machine', state)
    return (
        <div>State Machine</div>
    )
}

src/App.js:

import { BaseLayout } from './Components/BaseLayout';
import './App.css';

function App() {
  return (
    <div className="App">
        <BaseLayout />
    </div>
  );
}

export default App;

les recomiendo que copien el c贸digo manualmente en vez de copiar y pegar, ya que es todo nuevo ser铆a mejor familiarizarnos con la sintaxis y aprender el orden de cada cosa. Ya cuando estemos hartos de hacer tantas m谩quinas de estados haremos Ctrl + V xD

Declarar la maquina de estados

Para comenzar debemos inicializar nuestro proyecto en React.

Luego, vamos a usar el siguiente comando para instalar XState:

npm install xstate @xstate/react

Ahora por convenci贸n vanos a crear una nueva carpeta que se va a llamar machines, y dentro crearemos un un archivo llamado bookingMachine.js que ser谩 una serie de pasos senciila de la l贸gica de nuestra aplicaci贸n:

import { createMachine } from 'xstate';

const bookingMachine = createMachine({
  id: 'buy plane tickets',
  initial: 'initial',
  states: {
    initial: {
      on: {
        START: 'search'
      }
    },
    search: {
      on: {
        CONTIUNE: 'passengers',
        CANCEL: 'initial'
      }
    },
    passengers: {
      on: {
        DONE: 'tickets',
        CANCEL: 'initial'
      }
    },
    tickets: {
      on: {
        FINISH: 'initial'
      }
    },
  }
})

export default bookingMachine;

Ahora vamos a crear una nueva carpeta llamada components, y dentro crearemos un archivo BaseLayout.jsx.

/* Vamos a hacer import del hooks que necesitamos para inicializar 
la m谩quina "useMachine" y nuestro bookingMachine */
import { useMachine } from "@xstate/react";
import bookingMachine from "../machines/bookingMachine";

export const BaseLayout = () => {
  // Ahora vamos a inicializar la m谩quina de la siguiente manera:
  /* Vamoa a destructurar dos cosas del useMachine, la primera es el 
  "state", que nos d谩 toda la infromaci贸n de la m谩quina en ese 
  momento, y el send me permite transicionar entre distintos pasos,
  para esto, debe recibir la declaraci贸n de los estados entre 
  parentesis */
  const [state,send] = useMachine(bookingMachine);

  /* Si vemos en nuestra consola veremos nuestrab m谩quina de estado 
  inicializada, si vemos en value, si valor ser谩 el estado inicial, 
  el cual es "initial", junto con mucha m谩s informaci贸n */
  console.log('Nuestra m谩quina', state);

  return (
    <div>Hola :3</div>
  )
}

Ahora solo importamos el componente en App.jsx:

import BaseLayout from './components/BaseLayout';
import './App.css'

function App() {

  return (
    <div className="App">
      <BaseLayout />
    </div>
  )
}

export default App;

Y listo, as铆 de f谩cil hemos inicializado nuestra m谩quina de estado 馃槃.

Si usas yarn:

yarn create react-app my-app

npm me parece super lento.

Este es el procedimiento si vas a trabajar con React + TypeScript + Vite:

  • Primer paso: npm create vite@latest
  • Escoger React y typescript
  • Ingresar a la carpeta y usar el comando: npm i
  • (Opcional) Luego utilizar el comando git init para usar git en nuestro proyecto.
  • Ahora instalamos paquetes de xstate: npm i xstate @xstate/react
  • A codear!
En mi opinion, la carpeta seria m谩s legible como StateMachines/bookingMachine.js
En programaci贸n, espec铆ficamente en JavaScript o React, es com煤n que las carpetas y archivos que contienen componentes o m谩quinas de estados se nombren con la convenci贸n PascalCase, que consiste en iniciar cada palabra con may煤scula. Esto ayuda a distinguirlos f谩cilmente de otros archivos y carpetas que pueden no ser componentes. En el caso de "Machines", indica que es un m贸dulo espec铆fico relacionado con la l贸gica de la m谩quina de estados en el proyecto.
Vamos a inicializar nuestro proyecto usando `Create-React-App` y se llamar谩 `react-state-machine` . `npx create-react-app react-state-machine` Dentro del proyecto debemos instalar `XState` y el paquete de XState para React. `npm install xstate` `npm install @xstate/react` Solo queda correr el servidor para comenzar a trabajar en el proyecto. `npm run start` Creamos un nuevo folder llamado `Machines` y dentro de este un archivo `bookingMachine.js` . ```js import { createMachine } from 'xstate'; const bookingMachine = createMachine({ id: 'buy plane tickets', initial: 'initial', states: { initial: { on: { START: "search", }, }, search: { on: { CONTINUE: "passengers", CANCEL: "initial", }, }, passengers: { on: { DONE: "tickets", CANCEL: "initial", }, }, tickets: { on: { FINISH: "initial", }, } } }); export default bookingMachine; ``` En otra carpeta llamado `Components` vamos a crear un componente `BaseLayout.js` . ```js import React from "react"; import { useMachine } from "@xstate/react"; import bookingMachine from "../Machines/bookingMachine"; function BaseLayout() { const [state, send] = useMachine(bookingMachine); console.log(state); return
BaseLayout
; } export { BaseLayout }; ``` Importamos el hook `useMachine` que necesitamos para inicializar la m谩quina. Lo otro que tenemos que importar es nuestro Booking Machine. Vamos a inicializarla y esto me retorna `state` y `send` . El `state` me da toda la informaci贸n de la m谩quina en ese momento, y el `send` me permite generar transiciones. Finalmente, mostramos el estado de nuestra m谩quina. En `App.js` lo 煤nico que hacemos es utilizar nuestro componente. ```js import "./App.css"; import { BaseLayout } from "./Components/BaseLayout"; function App() { return (
<BaseLayout />
); } export default App; ```

EMPECE MI PROYECTO CON STATE MACHINE

Es un proyecto de pel铆culas, a煤n en proceso, solo est谩 disponible la vista mobile. Utilic茅 la m谩quina de estado para el nav.
https://my-movies-in-react.vercel.app/

npm i xstate @xstate/react