Skip to content

Instantly share code, notes, and snippets.

@cristiano-belloni
Last active March 26, 2020 16:45
Show Gist options
  • Save cristiano-belloni/fb3af1c6c0ada46b4d024e7a95ad77e1 to your computer and use it in GitHub Desktop.
Save cristiano-belloni/fb3af1c6c0ada46b4d024e7a95ad77e1 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const fetchMachine = Machine({
id: "contacts",
initial: "idle",
context: {
contactData: null,
contactsData: null,
contactId: null
},
states: {
idle: {
on: {
FETCH_CONTACT: {
target: "fetching_contact",
actions: [
assign({ loading: () => true }),
assign({ contactId: (_, event) => event.id })
]
},
FETCH_CONTACTS: {
target: "fetching_contacts",
actions: [
assign({
loading: () => true
}),
assign({
contactId: () => null
})
]
}
}
},
fetching_contact: {
invoke: {
id: "fetch-contact",
src: invokeFetchContact,
onDone: {
target: "idle",
actions: [
assign({ loading: () => false }),
assign({ contactData: (_, event) => event.data })
]
}
}
},
fetching_contacts: {
invoke: {
id: "fetch-contacts",
src: invokeFetchContacts,
onDone: {
target: "idle",
actions: [
assign({ loading: () => false }),
assign({ contactsData: (_, event) => event.data })
]
}
}
}
}
});
function invokeFetchContact(context) {
const { contactId } = context;
return fetch(
`https://jsonplaceholder.typicode.com/users/${contactId}`
).then(response => response.json());
}
function invokeFetchContacts() {
return fetch("https://jsonplaceholder.typicode.com/users/").then(response =>
response.json()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment