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);
}
};
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);
})
}
};