Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created March 1, 2023 18:19
Show Gist options
  • Save cambiata/2bba12cb47ecab69b0650bb0d9577750 to your computer and use it in GitHub Desktop.
Save cambiata/2bba12cb47ecab69b0650bb0d9577750 to your computer and use it in GitHub Desktop.
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