Skip to content

Instantly share code, notes, and snippets.

@oshimayoan
Last active September 25, 2020 08:10
Show Gist options
  • Save oshimayoan/83d4948c3015685ee972df3bdea90787 to your computer and use it in GitHub Desktop.
Save oshimayoan/83d4948c3015685ee972df3bdea90787 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 fetchedPosts = [...Array(10).keys()];
const hydrateCache = () => assign({
queryCache: (context) => context.asyncStorage
})
const storeToRecoil = () => assign({
recoil: (context) => {
let { recoil, queryCache } = context;
return {
posts: [
...queryCache.posts,
...recoil.posts,
]
}
}
});
const storeFetchedPosts = () => assign({
queryCache: {
posts: fetchedPosts,
}
});
const persistCache = () => assign({
asyncStorage: (context) => ({
posts: context.queryCache.posts
})
});
const retryFetch = () => assign({
retries: (context) => context.retries + 1
})
const postMachine = Machine({
id: 'posts',
initial: 'hydratingCache',
context: {
recoil: {
posts: []
},
asyncStorage: {
'posts': [100, 101, 102, 103]
},
queryCache: {},
retries: 0,
},
states: {
hydratingCache: {
on: {
HYDRATE_DONE: {
target: 'idle',
actions: hydrateCache()
}
}
},
idle: {
on: {
FETCH: {
target: 'fetching',
actions: storeToRecoil(),
}
}
},
fetching: {
on: {
RESOLVE: {
target: 'success',
actions: [
storeFetchedPosts(),
storeToRecoil(),
],
},
REJECT: 'failure',
}
},
success: {
on: {
PERSIST: {
target: 'persisting',
actions: persistCache()
}
}
},
persisting: {
type: 'final'
},
failure: {
on: {
RETRY: {
target: 'fetching',
actions: retryFetch(),
cond: (context) => {
return context.retries < 3
}
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment