javascript - Step by step dispatch in react redux, is it right? -
let's imagine have react redux application. application data server , append list (listappend action). in fetch process application shows loading bar (requestbegin, requestend actions). simple example bellow
export const fetchpagenum = () => { return (dispatch, getstate) => { ... dispatch(requestbegin()) return fetch(url).then((response) => { return response.json() }).then((json) => { dispatch(pagenumsuccess(page_num)) dispatch(listappend(json)) dispatch(requestend()) }).catch((error) => { dispatch(requestend()) }) } }
is correct use step step dispatch after request end?
it correct , technically called thunk
but since using es6, use new await
keyword, perhaps ending code looking this:
export const fetchpagenum = () => { return async (dispatch, getstate) => { try { dispatch(requestbegin()) const response = await fetch(url) const json = await response.json() dispatch(pagenumsuccess(page_num)) dispatch(listappend(json)) } catch (e) { // log error } dispatch(requestend()) } }
Comments
Post a Comment