Created
February 18, 2020 03:25
-
-
Save CAWeissen/c55618a79ec87f690ebbaeff115030be to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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
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