Last active
September 25, 2020 08:10
-
-
Save oshimayoan/83d4948c3015685ee972df3bdea90787 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
// 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