Skip to content

Instantly share code, notes, and snippets.

@mushfiqweb
Created May 28, 2021 12:38
Show Gist options
  • Select an option

  • Save mushfiqweb/ffd6f567a996ee4fd6a22a67875a10cb to your computer and use it in GitHub Desktop.

Select an option

Save mushfiqweb/ffd6f567a996ee4fd6a22a67875a10cb to your computer and use it in GitHub Desktop.
import { createMachine, interpret, assign } from 'xstate';
const fetchMachine = createMachine({
id: 'Dog API',
initial: 'idle',
context: {
dog: null
},
states: {
idle: {
on: {
FETCH: 'loading'
}
},
loading: {
invoke: {
id: 'fetchDog',
src: (context, event) =>
fetch('https://dog.ceo/api/breeds/image/random').then((data) =>
data.json()
),
onDone: {
target: 'resolved',
actions: assign({
dog: (_, event) => event.data
})
},
onError: 'rejected'
},
on: {
CANCEL: 'idle'
}
},
resolved: {
type: 'final'
},
rejected: {
on: {
FETCH: 'loading'
}
}
}
});
const dogService = interpret(fetchMachine)
.onTransition((state) => console.log(state.value))
.start();
dogService.send('FETCH');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment