I am trying to dispatch two posts at the same time using thunk in Redux but when I try to dispatch the second post I am missing the user id from the previous post. There might be a process on how to async chain these requests but I haven't been able find a good solution. It seems that userSelector supposed to keep its state. I have tried this link too: https://blog.jscrambler.com/async-dispatch-chaining-with-redux-thunk. Promise.all is not recommended but I also tried that as well as dispatch(…).then(() => dipatch()). Any feedback is great!!
import { configureStore, createAsyncThunk, createSlice, unwrapResult } from '@reduxjs/toolkit';
export const postInfo = createAsyncThunk(
'info/postInfo'
async (infoObject: InfoRequest) => {
const response = await axios.post(`${url}/info`, infoObject);
return response.data;
}
);
export const postSales = createAsyncThunk(
'sales/postSales'
async (salesObject: SalesRequest) => {
const response = await axios.post(`${url}/sales`, salesObject);
return response.data;
}
);
...
const postInfoSlice = createSlice<PostState, SliceCaseReducers<PostState>, string>({
name: 'postInfo',
sales: 'postSales',
initialState: {
request: { status: 'idle', error: '' },
},
reducers: {},
extraReducers: (builder) => {
builder.addCase(postInfo.fulfilled, (state, action) => {
state.request.status = 'succeeded';
state.model = action.payload;
}
builder.addCase(postInfo.rejected, (state, action) => {
state.request.status = 'failed';
state.request.error = action.error.message as string;
})
builder.addCase(postSales.fulfilled, (state, action) => {
state.request.status = 'succeeded';
state.model = action.payload;
}
builder.addCase(postSales.rejected, (state, action) => {
state.request.status = 'failed';
state.request.error = action.error.message as string;
})
},
})
...
const store = configureStore({
reducer:
postInfoSlice.reducer
});
export type RootState = ReturnType<typeof store.getState>;
constant user = useSelector((state: RootState) => state.postState.user);
const sendInfoRequest = async () => {
try {
const infoObjRequest: InfoRequest = {
firstName: 'John',
lastName: 'Smith'
};
await dispatch(postInfo(infoObjRequest)).unwrap();
} catch (err) {
console.log('rejected for post /info', err);
}
};
const sendSalesRequest = async () => {
try {
const salesObjRequest: SalesRequest = {
firstName: 'John',
lastName: 'Smith',
userId: user?.id
};
await dispatch(postSales(salesObjRequest)).unwrap();
} catch (err) {
console.log('rejected for post /sales', err);
}
};
// Here is where I am dispatching both post where sendSalesRequest can't get the user id from previous postInfo.
sendInfoRequest();
sendSalesRequest();