Created
January 23, 2020 20:44
-
-
Save barbados-clemens/995aaf1591356f86cdf9ef4dc04001b2 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Tutorial from docsk | |
// https://xstate.js.org/docs/tutorials/reddit.html#modeling-the-app | |
// Sample SELECT Event | |
const selectEvent = { type: 'SELECT', name: 'reactjs' }; | |
const invokeFetchSubreddit = context => { | |
const {subreddit} = context; | |
return fetch(`https://www.reddit.com/r/${subreddit}.json`) | |
.then(res => res.json()) | |
.then(json => json.data.children.map(child => child.data)); | |
} | |
const redditMachine = Machine({ | |
id: 'reddit', | |
initial: 'idle', | |
context: { | |
subreddit: null, | |
posts: null | |
}, | |
states: { | |
idle: {}, | |
selected: { | |
initial: 'loading', | |
states: { | |
loading: { | |
invoke: { | |
id: 'fetch-subreddit', | |
src: invokeFetchSubreddit, | |
onDone: { | |
target: 'loaded', | |
actions: assign({ | |
posts: (context, event) => event.data | |
}) | |
}, | |
onError: 'failed', | |
} | |
}, | |
loaded: {}, | |
failed: {} | |
} | |
} | |
}, | |
on: { | |
SELECT: { | |
target: '.selected', | |
actions: assign({ | |
// event.name is from .send passed in data | |
subreddit: (context, event) => event.name | |
}) | |
} | |
} | |
}, {devTools: true}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment