Maya Shavin
@mayashavin
@mayashavin
On bus
Check-in
Arrive by air
Arrive to station
Reach the hotel
Travel by train
@mayashavin
@mayashavin
When something happens, how do the app react?
Events
Behaviors (states)
@mayashavin
State
State
State
Event
Event
Event
Finites of States
Transition using Event
State data control using Actions
@mayashavin
@mayashavin
How many lines of if...else if... (or switch...case) is enough?
@mayashavin
The JS State Machines Library
@mayashavin
npm i xstate @xstate/react
const fetchMachine = createMachine({
id: 'fetch',
initial: 'idle',
context: { retries: 0 },
states: {
idle: {
on: {
FETCH: 'loading'
}
},
loading: {
on: {
RESOLVE: 'success',
REJECT: 'failure'
}
},
success: {
type: 'final'
},
failure: {
on: {
RETRY: {
target: 'loading',
actions: assign({
retries: (context, event) => context.retries + 1
})
}
}
}
}
});
@mayashavin
import { interpret } from 'xstate';
const machine = createMachine({/* configuration */})
const service = interpret(machine)
service.onTransition(newState => {
/* do something during transition from one state to another */
}).start();
service.send('EVENT');
import { myMachine } from '../machines/myMachine';
import { useActor, useInterpret } from '@xstate/react'
export const useMyMachine = () => {
const service = useInterpret(myMachine);
const [state, send] = useActor(service);
return [state, send];
}
React
Seeing is believing... as always
@mayashavin
React XState XState/vue XState/inspect XState/graph
@mayashavin
@mayashavin
@mayashavin
@mayashavin
@mayashavin
@mayashavin
Senior Software Engineer
MICROSOFT
Core Team
STOREFRONT-UI
Organizer
VUEJS ISRAEL
Blogger & Book Author
@mayashavin
mayashavin.com
@mayashavin
mayashavin.com