Skip to content

Instantly share code, notes, and snippets.

@oshimayoan
Last active September 28, 2020 09:39
Show Gist options
  • Save oshimayoan/e5f050bfc9a0ca794dd44ad4742609a4 to your computer and use it in GitHub Desktop.
Save oshimayoan/e5f050bfc9a0ca794dd44ad4742609a4 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)
let fetchedComments = [...Array(10).keys()];
const hydrateCache = () => assign({
queryCache: (context) => context.asyncStorage
})
const storeToRecoil = () => assign({
recoil: (context) => {
let { recoil, queryCache } = context;
return {
comments: {
...recoil.comments,
'postId_1': queryCache['postId_1']
}
}
}
});
const storeFetchedComments = (status) => assign({
queryCache: (context) => {
if (status === 'mutate') {
let newComment = fetchedComments.length
fetchedComments.push(newComment)
}
return {
...context.queryCache,
'postId_1': fetchedComments,
}
}
});
const addComment = () => assign({
recoil: (context) => {
let { comments } = context.recoil;
return {
comments: {
'postId_1': [
...comments['postId_1'],
new Date().getTime(),
]
}
}
}
});
const persistCache = () => assign({
asyncStorage: (context) => ({
'postId_1': [
...context.queryCache['postId_1']
]
})
});
const retryFetch = () => assign({
fetchRetries: (context) => {
return context.fetchRetries + 1
}
})
const commentsMachine = Machine({
id: 'comments',
initial: 'hydratingCache',
context: {
recoil: {
comments: {}
},
asyncStorage: {
'postId_1': [1, 2, 3, 4]
},
queryCache: {},
fetchRetries: 0
},
states: {
hydratingCache: {
on: {
HYDRATE_DONE: {
target: 'idle',
actions: hydrateCache()
}
}
},
idle: {
on: {
FETCH: {
target: 'fetching',
actions: storeToRecoil(),
},
ADD_COMMENT: {
target: 'addingComment',
actions: addComment(),
cond: (context) => Object.keys(context.recoil.comments).length
},
}
},
fetching: {
on: {
FETCH_RESOLVED: {
target: 'fetchSuccess',
actions: [
storeFetchedComments(),
storeToRecoil(),
]
},
FETCH_REJECTED: 'fetchFailure',
}
},
fetchFailure: {
on: {
RETRY: {
target: 'fetching',
actions: retryFetch(),
cond: (context) => {
return context.fetchRetries < 3
}
},
NETWORK_ERROR: {
target: 'idle',
cond: (context) => {
return context.fetchRetries >= 3
}
}
}
},
fetchSuccess: {
on: {
PERSIST: 'persisting',
}
},
addingComment: {
on: {
MUTATE: 'mutating',
}
},
mutating: {
on: {
MUTATE_RESOLVED: {
target: 'mutateSuccess',
// TODO: create better function
actions: [
storeFetchedComments('mutate'),
storeToRecoil()
]
},
MUTATE_REJECTED: 'mutateFailure',
}
},
mutateSuccess: {
on: {
PERSIST: 'persisting'
}
},
persisting: {
on: {
PERSIST_DONE: {
target: 'idle',
actions: persistCache(),
}
}
},
// TODO: do something
mutateFailure: {},
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment