Skip to content

Instantly share code, notes, and snippets.

@CAWeissen
Created February 18, 2020 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CAWeissen/c55618a79ec87f690ebbaeff115030be to your computer and use it in GitHub Desktop.
Save CAWeissen/c55618a79ec87f690ebbaeff115030be to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const apiBase = '/api';
const endpoint = '/presentations';
const getPresentations = () =>
fetch(`${apiBase}${endpoint}`)
.then(response => response.json());
const searchPresentations = (query) =>
fetch(`${apiBase}${endpoint}/?search=${query}`)
.then((response) => response.json());
const updatePresentations = (id, presentation, presentations) =>
fetch(
`${apiBase}${endpoint}/${id}`,
{
method: 'post',
body: JSON.stringify(presentation)
})
.then(response => response.json())
.then(() => {
const index = presentations.findIndex(p => p.id === presentation.id);
presentations[index] = presentation;
return presentations;
});
const presentationsMachine = Machine(
{
id: 'presentations',
initial: 'ready',
context: {
loading: false,
presentations: [],
},
states: {
ready: {
on: {
GET: 'getting',
SEARCH: 'searching',
UPDATE: 'updating',
}
},
getting: {
entry: assign({loading: true}),
invoke: {
id: 'getPresentation',
src: () => getPresentations(),
onDone: {
target: 'ready',
actions: assign({
loading: false,
presentations: (_context, event) => []
})
}
}
},
searching: {
entry: assign({loading: true}),
invoke: {
id: 'searchPresentations',
src: (_context, event) => searchPresentations(event.query),
onDone: {
target: 'ready',
actions: assign({
loading: false,
presentations: (_context, event) => []
})
}
}
},
updating: {
invoke: {
id: 'updatePresentations',
src: ({presentations}, event) => updatePresentations(event.id, event.presentation, presentations),
onDone: {
target: 'ready',
actions: assign({
presentations: ({presentations}, event) => {
return [];
}
})
}
}
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment