简体   繁体   中英

dispatching Asynchronous action from an array react redux thunk

As per the requirement we need to make API call from the array list.Have used redux-thunk for async operation.Having issues while passing the request parameter to the reducer after api call is finished.

    # From the container
    let document = [ bankstatement1,bankstatement2];
    document.map(element => {
     dispatch ( actions.uploadFiles(element) )
    });
    # inside actions
    export const uploadFiles = (payload) => {
      return async dispatch => {
        
        const response = await callAPIMiddleware(dispatch, {
          types: ['DOC_UPLOAD_START','DOC_UPLOAD_SUCCESS','DOC_UPLOAD_ERROR'],
          endPoint: ApiEndpoints.DOCUMENT_UPLOAD,
          type: HTTP_METHOD_TYPE.POST,
          payload: payload,
          headers: Headers.multipart,
          
        });
        return response;
      };
    };
    # inside axios middle ware
    export const callAPIMiddleware = async (dispatch, RequestParams) => {
     # calling upload_start ,here also the request payload being asked.     
        dispatch({
            type: "DOC_UPLOAD_START,
            data:RequestParams //bankstatement1,bankstatement2
          });
    
    # let res = await axios.post(endPoint,RequestParams, {
            headers: reqHeaders,
            config: reqConfig,
            });
    if (res && res.data) {
         
            dispatch({
              type:'DOC_UPLOAD_SUCCESS',
              data: res.data,
              param:RequestParams //bankstatement2,bankstatement2 here it is always referring to "bankstatement2" 
            });
    
    }
After the API call is finished, reference to first request parameter is overridden by second one.Can anyone suggest how we can still refer to the first element .

EDITED: what if you try to place the last piece of logic in "then" so it surely scoped there?

axios.post(endPoint,RequestParams, {
  headers: reqHeaders,
  config: reqConfig,
  }).then(res => {
    console.log('calling dispatch for ', RequestParams);
    if (res && res.data) {
      dispatch({
        type:'DOC_UPLOAD_SUCCESS',
        data: res.data,
        param: RequestParams,
      });
    } else {
      console.log('oops no result for ', RequestParams);
    }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM