Last active
September 16, 2019 13:30
-
-
Save elsangedy/4562d68f1e733c13cc74cf2104a83f50 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 fetchMachine = Machine({ | |
id: "infinite-scroll", | |
initial: "idle", | |
context: { | |
page: 1, | |
size: 2, | |
total: 0, | |
keyword: "", | |
items: [] | |
}, | |
states: { | |
idle: { | |
on: { | |
SEARCH: { | |
target: "searching", | |
actions: assign({ page: 1, keyword: (_, event) => event.keyword }), | |
cond: 'notSameKeyword' | |
}, | |
FETCH_MORE: { | |
target: "fechingMore", | |
cond: "hasMore", | |
actions: assign({ page: context => context.page + 1 }) | |
} | |
} | |
}, | |
searching: { | |
invoke: { | |
id: "search", | |
src: "onFetch", | |
onDone: { | |
target: "idle", | |
actions: assign((_, event) => event.data) | |
}, | |
onError: { | |
target: "idle" | |
} | |
} | |
}, | |
fechingMore: { | |
invoke: { | |
id: "fetchMore", | |
src: "onFetch", | |
onDone: { | |
target: "idle", | |
actions: assign((context, event) => ({ | |
...event.data, | |
items: [...context.items, ...event.data.items] | |
})) | |
}, | |
onError: { | |
target: "idle" | |
} | |
} | |
} | |
} | |
}, | |
{ | |
guards: { | |
hasMore: (context, event) => { | |
return context.page < Math.ceil(context.total / context.size); | |
}, | |
notSameKeyword: (context, event) => { | |
return context.keyword !== event.keyword | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment