I’ve been working on an issue that involves making a call in uploading a file via an asyncThunk call. Once that call is complete, it returns a payload of the filePath.
From there I am attempting to update the state of an object called “transaction” within the “addCase” code block for when the uploadFileAsyncThunk.fulfilled so that it can be saved in the database. Everything functions as it should, except the order in which the code executes is not how I would expect it to be. It appears that the state does not update at the time the transaction object is sent to the second asyncThunk (postTransactionThunk).
Debugging through the code, I can see that the uploadResultAction is populated with the return data I expect. and the uploadFileThunk.fulfilled.match(uploadResultAction)
is valid to proceed through the rest of the code. From there, getting the filePathParam does contain the data I want and dispatching the data does work. I can console log at the top of the component that my data has been updated. However, when I see the state through Redux DevTools. My state doesn’t update until dispatchPostTransactionThunk
is executing, which at that point is too late because the transaction data being referenced for POST is outdated.
How do I update my transaction
state so that I am able to execute postTransactionThunk with the most updated data?
const uploadResultAction = await dispatch(uploadFileThunk(file));
if (uploadFileThunk.fulfilled.match(uploadResultAction)) {
const filePathParam =
{
filePath: uploadResultAction.payload.response,
};
dispatch(updateTransaction(filePathParam));
const postTransactionResultAction = await dispatch(postTransactionThunk(transaction));
if (postTransactionThunk.fulfilled.match(
postTransactionResultAction)) {
// ...
}
}
Here is my reducer logic for updating the transaction upon fulfilled:
.addCase(uploadFileThunk.fulfilled, (state, action) => {
return {
...state,
loading: false,
error: null,
fileUploadResponse: action.payload,
transaction: {
...state.transaction,
filePath: action.payload.response,
},
};
})
I’ve tried debugging through the code. I’ve also tried placing cascading .then(…) blocks between each dispatch call which didn’t make a difference either.