Answer the question
In order to leave comments, you need to log in
How to execute an action only after dispatch of an asynchronous function?
Good afternoon.
I have the following function in a component:
function uploadFile(canvas, crop) {
if (!crop || !canvas) {
return;
}
canvas.toBlob(async (blob) => {
const formData = new FormData();
formData.append('file', blob);
dispatch(updateAvatar({ file: formData, userId: user._id }));
setIsOpen(false);
setUpImg(null);
setCompletedCrop(null);
});
}
export const updateAvatar = createAsyncThunk(
'user/updateAvatar',
async ({ file, userId }, thunkApi) => {
try {
const response = await UserService.updateAvatar(file, userId);
return response.data;
} catch (err) {
...
}
const response = await UserService.updateAvatar(formData);
dispatch(updateAvatar(response.data));
action={async (formData) => {
return dispatch(updateAvatar({ file: formData, userId: user._id }));
}}
function uploadFile(canvas, crop) {
if (!crop || !canvas) {
return;
}
canvas.toBlob(async (blob) => {
const formData = new FormData();
formData.append('file', blob);
const test = await action(formData);
if (test.meta.requestStatus !== 'pending') {
setIsOpen(false);
setUpImg(null);
setCompletedCrop(null);
}
});
}
Answer the question
In order to leave comments, you need to log in
If this dispatch is from useReducer, then it only schedules some data changes that will only be applied in the next render cycle. Playing with async won't help. You need to use useEffect so that if some variable in the state changes, useEffect cleans up the variables.
For example
useEffect(() => {
setIsOpen(false);
setUpImg(null);
setCompletedCrop(null);
},[uploaded])
When working with React, any change in the interface must be reflected in the state. If you need to receive data asynchronously, then your component will have at least 3 states: data at initialization, waiting for loading, data received. Also, dispatch is always synchronous, which is why we need libraries like React Thunk that do lazy state changes. Therefore, writing asynchronous actions without calling dispatch is wrong.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question