hi i'm new react/redux development environment appreciate help.
i'm trying make 2 api calls asynchronously when componentdidmount
calling dispatch(fetchallpositions(selecteduserdivision))
in app.js
i found suggested method in this post , fetchallpositions
function wraps 2 action functions in promise.all
export function fetchallpositions(division) { return dispatch => promise.all([ dispatch(fetchuserpositionsifneeded(division)), dispatch(fetchdefaultpositionsifneeded(division)) ]) .then(console.log("fetched both")) }
the 2 action functions identical, call different api url. 1 of them looks follows, shouldfetchuserposition
pure function returns boolean:
function fetchuserpositions(division) { return dispatch => { const url = apioptions.server + `/api/user/position?division=${division}` dispatch(requestuserpositions(division)) return fetch(url, options) .then(response => response.json()) .then(json => dispatch(receiveuserpositions(division,json)), err => console.log(err)) } } export function fetchuserpositionsifneeded(division) { return (dispatch, getstate) => { if (shouldfetchuserpositions(getstate(), division)) { return dispatch(fetchuserpositions(division)) } else { return promise.resolve() } } }
the logic update, request...
action sent while pulling data, receive...
action sent when data ready updated new state.
the trouble promise.all
should wait request1
request2
receive1
receive2
come in before doing .then(console.log("fetched both"))
right now, it's .then
after first 2 request
finished, not waiting 2 receive
come in.
i suspect it's nested nature of requestuserpositions()
within function wraps fetch()
the request
action simple function, , in reducer flips isfetching
property true
:
function requestuserpositions(division) { return { type: request_user_positions, division } }
sorry long issue i'd appreciate suggestions.
this careless mistake
turns out when .then()
wrapped inside dispatch gets executed simultaneously promise.all()
being carried out.
the intended dispatch order created tagging then(()=>console.log
last dispatch dispatch(fetchallpositions(selecteduserdivision))
done componentdidmount
Comments
Post a Comment