Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created March 6, 2023 13:20
Show Gist options
  • Save cambiata/433ffc6c7efb943c36b8255f4de60f68 to your computer and use it in GitHub Desktop.
Save cambiata/433ffc6c7efb943c36b8255f4de60f68 to your computer and use it in GitHub Desktop.
type LoadingState =
| { type: 'empty' }
| { type: 'loading', progress: number }
| { type: 'success', result: number }
| { type: 'error', msg: string }
const loadingMachine = createMachine({
id: 'machine',
initial: 'active',
states: {
active: {
invoke: {
src: () => (callback, _) => {
let loadProgress = 0;
const id = setInterval(() => {
loadProgress += 1;
loadProgress < 5 ?
callback({ type: 'LOADING', data: { state: 'loading', progress: loadProgress } })
: callback({ type: 'SUCCESS', data: { state: 'success', result: 123 } });
}, 500);
return () => {
console.log('clear invoke service...');
clearInterval(id)
};
}
},
on: {
LOADING: {
actions: [
(context, event) => { console.log('LODING', JSON.stringify(event)) },
sendParent((context, event) => ({ type: 'LOADING_STATE', data: event.data })),
]
},
SUCCESS: {
actions: [
(context, event) => { console.log('LODING', JSON.stringify(event)) },
sendParent((context, event) => ({ type: 'LOADING_STATE', data: event.data })),
],
target: 'finished',
},
}
},
finished: {
entry: [
(c, e) => { console.log('finished'); console.log(e); },
],
type: 'final',
}
}
}, {
})
type ParentState = {
loading: LoadingState,
}
const parentMachine = createMachine<ParentState>({
id: 'parent',
initial: 'active',
context: {
loading: { type: 'empty' },
},
states: {
active: {
invoke: {
src: loadingMachine,
onDone: {
target: 'done',
}
},
on: {
LOADING_STATE: {
actions: [
(c, e) => console.log('parent LOADING STATE action: ' + JSON.stringify(e)),
assign((context, event) => ({ ...context, loading: event.data })),
]
}
}
},
done: {
}
}
})
const service = interpret(parentMachine)
.onTransition((state) => console.log(JSON.stringify(state.context)));
service.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment