Created
March 1, 2023 18:19
-
-
Save cambiata/2bba12cb47ecab69b0650bb0d9577750 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FetchMachineContext = | |
| { | |
status: 'text', | |
text: string, | |
} | |
| { | |
status: 'empty' | |
} | |
export type FetchMachineEvent = | |
| { | |
type: 'LOAD'; | |
loadId: number; | |
}; | |
const fetchMachine = createMachine<FetchMachineContext, FetchMachineEvent>({ | |
id: 'fetchMachine', | |
initial: 'start', | |
context: { status: "empty" }, | |
states: { | |
start: { | |
entry: (context, event) => { console.log('enter state start'); }, | |
on: { | |
"LOAD": { | |
target: "load" | |
}, | |
}, | |
exit: (context, event) => { console.log('exit state start') }, | |
}, | |
load: { | |
entry: (context, event) => { console.log('enter state load'); }, // ["notifyStart"] | |
invoke: { | |
src: async (context, event) => { | |
console.log('fetchSomething', event); | |
const response = await fetch('/data.txt'); | |
// throw new Error("ERROR TJOHOO"); | |
const text = await response.text(); | |
return text; | |
}, | |
onError: { | |
actions: (context, event) => alert(JSON.stringify(event)), | |
}, | |
onDone: { | |
actions: assign((context, doneEvent): FetchMachineContext => { | |
console.log('onDone action', doneEvent); | |
return { status: 'text', text: doneEvent.data }; | |
}), | |
target: "loaded", | |
} | |
}, | |
exit: (context, event) => { console.log('exit state loading') }, | |
}, | |
loaded: { | |
entry: (context, event) => { console.log('enter state loaded'); }, | |
} | |
} | |
}, { | |
// services: { | |
// fetchSomething: (context, event) => { | |
// console.log('fetchSomething', event); | |
// return fetch('/data.txt').then(response => response.text()) | |
// } | |
// } | |
}); | |
const fetchService = interpret(fetchMachine).onTransition((state) => console.log(state.context)).start(); | |
fetchService.send({ type: "LOAD", loadId: 123 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment