single reducer for multiple async calls in react ,redux Code Answer

I am calling single post request multiple times like below from a component in React js:

Object.keys(data).map(account => {
    const accountRequest = {
        accountNo: account.accountNo,
        id : account.id
    }
    return this.props.requestAccountDetails(accountRequest)
}

requestAccountDetails is a function written in const mapDispatchToProps in container:

const mapDispatchToProps = (dispatch)  => {
    return {
        requestAccountDetails : (accountDetails)=> {
            dispatch(requestAccountDetailsInformation(accountDetails));
        }
    }
}

requestAcountDetailsInformation is an action written in action creator which calls redux-saga which is called multiple times asynchronously depending on no of accounts. So, if say number of accounts is 5 , post request I am calling is 5 times asynchronously using redux-saga.

Issue is when my post request gets returned successfully, I am again calling success action which calls reducer and data is supplied to my component.But as the call is made 5 times and it is calling same success function and same reducer.It overwrites previous call result. Example: If my first request returns result, and second request returns result.My first request result is overwritten in reducer.

Can anyone help me how can I maintain result of all 5 requests in single reducer.

Answer

you need to add result in array rather than overwrite in it. let say you have state.

const state = {
accountDetails =[]
}

In reducer in success call you can push new data in accountDetails and update state.

  reducer(initialState=state, action)
    switch(action.type){
      ....
    case Authsuccess: return { ...initialState,
                                accountDetails : [ 
                                ...initialState.accounDetails, 
                                 action.payload.accountInfo
                                 ],
                              }
           

                                  

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji