API fetching with xstate in React

198 views Asked by At

I am working on a React application which calls a GET request and then waits for a response which it then goes through conditions where depending on the condition, a component renders on the page.

How can I implement this with xstate to handle the various conditions?

I made my machine like this:

import { createMachine, assign } from 'xstate'

const fetchData = async (context, event) => {
  const { token } = event.params;
  try {
    const res = await fetch(api) // Fetching API here
enter code here
     // Here are some conditions that I am going to use to render data
enter code here
  } catch (error) {
    return { type: 'error', renderType: 'error' }
  }
}


const interviewMachine = createMachine(
  {
    id: 'myMachine',
    initial: 'idle',
    context: {
     // Some values for rendering component based on it
    },

    states: {
      idle: {
        on: {
          FETCH: {
            target: 'loading',
            actions: 'fetchData'
          }
        }
      },

      loading: {
        invoke: {
          src: fetchData,
          onDone: { target: 'Component To Render' }
        },
      },

      error: {},
      success: {},

      'Component To Render': {
        on: {
            target: 'loading',
            actions: ['fetchData', ...other actions],
        },
      },

      OtherComponentToRenderBasedonAction: {
        on: {
            target: 'loading',
            actions: ['fetchData', ...other actions],
        },
      },
    },
  },
  {
    actions: {
      fetchData,
    ...
    },
  },
)

export default myMachine

I added what is I am trying for xstate machine, and the above logic caused errors. I need to know if there is something wrong with itand. How can I handle this in a better way?

1

There are 1 answers

0
Jonas Nutels On

If I understand correctly, you want:

import { Machine } from 'xstate';

const appMachine = Machine({
  id: 'app',
  initial: 'loading',
  states: {
    loading: {
      on: {
        SUCCESS: 'success',
        ERROR: 'error',
      },
    },
    success: {},
    error: {},
  },
});

enter code here