I'm testing out simple paging with react hooks, and wondering how to deal with failures to keep it valid in state?
Pseudo code:
function reducer(state, action) {
switch (action.type) {
case 'next':
return {page: state.page + 1};
case 'prev':
return {page: state.page - 1};
default:
throw new Error();
}
}
function Page() {
const [state, dispatch] = useReducer(reducer, { page: 1});
useEffect(() => {
loadMore(state.page)
.then(r => console.log(r))
.catch(e => {
// how to revert page without triggering this effect?
// cause if I do dispatch({type: 'prev'}) page will change, and this will re-run
console.log(e)
})
}, state.page)
return (
<>
Page: {state.page}
<button onClick={() => dispatch({type: 'prev'})}>-</button>
<button onClick={() => dispatch({type: 'next'})}>+</button>
</>
);
}
Let's take this scenario:
- we start with page 1
- user clicks next
- page is increased in state
- useEffect fires, network request fails.
- page in state is 2, but actual data is of page 1
I cannot dispatch page change event on catch, because it would trigger refetch, which I don't want to do
Another option about which I was thinking was that I should maybe increment page only after I've got the data for it, but then I would create infinite loop in useEffect cause page would change after fetching data?