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:

2 Días
18 Hrs
22 Min
55 Seg

Acciones

9/15
Resources

What are actions in a state machine?

Actions in state machines are functions that are executed during certain key moments within the state transition. They can be triggered when entering or leaving a state, or even during the transition itself. The particularity of actions is that they are executed only once when they are triggered, concluding immediately afterwards.

How do entry actions work?

Entry actions are executed when a new state is entered. For example, when entering a state called "search", you might need to perform a search for possible countries using an endpoint. In this case, you could execute an input action that makes the necessary request to get those countries.

What are exit actions?

Exit actions, on the other hand, are triggered before changing state. Imagine a form where a user enters their personal data. Before changing to the next state, you can execute an exit action that sends this data to the backend via an endpoint. This ensures that the information is processed before the application state changes.

Implementing actions in code

Implementing actions in a state machine involves defining when and how they are executed. The following describes how to do this with a practical example.

How to define an action during transition?

To create an option to be executed during a transition, we must first modify the start event. We change our current target to an object that includes the action to be executed:

// Change the target to an object with actionsconst target = { target: 'search', actions: 'printStart'};

That printStart should be defined as a function that logs a console.log showing "printStart". We make sure to place this function outside the states of our machine:

const actions = { printStart: () => console.log('Print Start')};

How to define input and output actions for a state?

To define input and output actions, we declare them inside the state, before the on section. So, for the "search" state, we could define them as follows:

const search = { entry: ['printInput'], exit: ['printOutput']};

These actions conform to functions that must be created appropriately:

const actions = { printInput: () => console.log('Print input to search'), printOutput: () => console.log('Print output from search')};

Practical tips for implementing actions

  • Clear code structure: make sure that the corresponding actions and functions are well placed outside the main state objects to avoid errors.
  • Testing and validation: After implementing an action, test your state machine and verify that the logs run as expected.
  • Maintenance and scalability: Organize functions and actions in a modular fashion to facilitate modification or expansion of functionality.

With these concepts, you now have a solid foundation for implementing and using actions in your JavaScript state machines - continue exploring and implementing more cases to consolidate your learning! We look forward to seeing you in the next class to dive into context and its relationship with actions.

Contributions 7

Questions 3

Sort by:

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

💃 Acciones

Ideas/conceptos claves

Accion

Es una función que se ejecuta cuando estamos dentro de un estado

Apuntes

  • Una acción puede ser:
    • De entrada
      • Se disparan cuando entramos a un nuevo estado
    • De salida
      • Se disparan cuando salimos de un estado
    • Durante una transición
      • Se invoca cuando estamos en proceso o terminando una transición
  • Las acciones cuando las invocamos se llaman una sola vez y finaliza

lo que entendí de la case

Podemos implementar acciones cuando se hace el cambio de un estado a otro, estas acciones pueden ser:

  • De entrada
  • De salida
  • Durante una transición

creamos estas acciones pasándole como segundo parámetro a createMachine un objeto con una propiedad actions la cual contiene un objeto con las funciones o acciones que deseamos implementar

const bookingMachine = createMachine( {... }, {
  actions: {
    printTransition: ()=> console.log('transition'),
    printTransitionTwo: ()=> console.log('transition two'),
    printEntry: ()=> console.log('entry'),
    printExit: ()=> console.log('exit')
  }
})

lo implementamos pasándole nuevas propiedades a los estados
.
.
sea una acción de entrada:

search: {
  entry: 'printEntry', // de entrada 
  on: {
    CONTINUE: "passengers",
    CANCEL: "initial",
  },
}

de salida:

search: {
  exit: 'printExit', // de salida 
  on: {
    CONTINUE: "passengers",
    CANCEL: "initial",
  },
}

o durante una transición pasándole como parámetro al estado un objeto con una propiedad target que contiene el nombre del siguiente estado, y una propiedad actions que contiene la acción a ejecutar

initial: {
  on: {
    START: { 
      target: 'search', // siguiente estado
      actions: 'printTransition' // accion a ejecutar 
    },
  },
}

o acciones pasándole como parámetro a la propiedad actions un array con las acciones que deseamos ejecutar

initial: {
  on: {
    START: { 
      target: 'search',
      actions: ['printTransition', 'printTransitionTwo'] // acciones a ejecutar 
    },
  },
}

Las **ACCIONES** son funciones o comandos que se ejecutan antes o después de un evento o durante una transición. Me resultó sencillo entender el tema haciendo una comparación con **TRIGGERS** en una BD.
En el momento en que realizo el curso, la versión 5 de XState está disponible y trae varios cambios, y uno de ellos es que ahora podemos ejecutar funciones directamente en actions, quedando algo así: ```js import { createMachine } from "xstate"; export const bookingMachine = createMachine({ id: "buy plane tickets", initial: "initial", states: { initial: { on: { START: { target: "search", actions: () => console.log("print init"), }, }, }, search: { on: { CONTINUE: "passengers", CANCEL: "initial", }, }, tickets: { on: { FINISH: "initial", }, }, passengers: { on: { DONE: "tickets", CANCEL: "initial", }, }, }, }); ```O si quieres algo más modular o si necesitas reutilizar esa acción, también puedes extraerla y ejecutarla en actions, de esta manera: ```js import { createMachine } from "xstate"; const logHomeAction = () => console.log("print home"); export const bookingMachine = createMachine({ id: "buy plane tickets", initial: "initial", states: { initial: { on: { START: { target: "search", actions: logHomeAction, }, }, }, search: { on: { CONTINUE: "passengers", CANCEL: "initial", }, }, tickets: { on: { FINISH: "initial", }, }, passengers: { on: { DONE: "tickets", CANCEL: "initial", }, }, }, }); ```

para los que quieran utilizar una lista con todos los paises.

import React, { useState, useEffect } from 'react';
import './Search.css';

export const Search = ({ send }) => {
  const [flight, setFlight] = useState('');
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    // Obtener la lista de países desde la API de REST Countries
    fetch('https://restcountries.com/v3.1/all')
      .then(response => response.json())
      .then(data => {
        const countryNames = data.map(country => country.name.common);
        setCountries(countryNames);
      })
      .catch(error => console.error('Error fetching countries:', error));
  }, []);

resto del codigo…

Me viene un ejemplo de poder hacer un step progress bar para un form de registro o como este caso, una compra.

Buena!!