Home > Net >  Waiting for dispatch in thunks
Waiting for dispatch in thunks

Time:01-26

I need to wait until dispatch in thunks is done. After that, I have to set state of hook to true.

Here is my service:

   export const loadSearchInfoAsync = (product_id: string) => {
      return (dispatch: Dispatch) => {
        SearchService.getSearchInfo(product_id)
          .then((response) => {
            if (response) {

              // Wait until this dispatch is done
              dispatch(searchInfoLoadSuccess(response.data));

            }
          })
          .catch((error) => {
            if (error) {
              dispatch(appErrorState(error.response));
            }
          });
      };
    };

And here is state which has to be updated after that dispatch

  const handleScan = (data: string | null) => {
    if (!proceed && data) {

      // After this dispatch make setProceed true
      dispatch(loadSearchInfoAsync(data));
      setProceed(true);
    }
  };

CodePudding user response:

Maybe it will help you

const loadSearchInfoAsync = (product_id: string, onSuccess, onFailure) => {
return (dispatch: Dispatch) => {
  SearchService.getSearchInfo(product_id)
    .then((response) => {
      if (response) {

        // Wait until this dispatch is done
        dispatch(searchInfoLoadSuccess(response.data));
        onSuccess()
      }
    })
    .catch((error) => {
      if (error) {
        dispatch(appErrorState(error.response));
        onFailure()
      }
    });
};

};

 const loadSearchInfoPromise = (product_id: string) => {
return new Promise((resolve, reject) => {
  dispatch(loadSearchInfoAsync(product_id, resolve, reject))
}

}

 const handleScan = async (data: string | null) => {
if (!proceed && data) {

  // After this dispatch make setProceed true

  await loadSearchInfoPromise(data).then(() => {
    setProceed(true);
  })
}

};

CodePudding user response:

I think in this case you could probably just move your proceed code into an effect and wait for a response on that?

useEffect(() => {
  if (data.length) { // or do whatever check here to see if it's not empty
    setProceed(true);
  }
}, [data])
  •  Tags:  
  • Related