I have a function in a component that adds an entry to my state 1 (in Redux via RTK).
The api returns me the auto-generated id of this new entry and I add it to state 1.
I then need to create an entry in a second state 2 (linked table), using the id of the state 1 entry mentioned above.
My problem is that my state 1 is not directly updated in the component and it is only updated after the entire function has been completed so I don't have access to the id of the new entry of the state 1 at the right moment.
How can I access this new value and especially the id in the function of the component?
State 1
const spectacles = useAppSelector(spectacleSelector.selectAll);
Function to add an entry in the state 1
const handleCreateClick = () => {
MySwal.fire({
// not needed code
}).then((result) => {
if (result.isConfirmed) {
dispatch(createSpectacleAsync(result.value!))
.then(() => dispatch(createSiteDeTirAsync({ id_Spe: spectacles[spectacles.length - 1]?.id!, code: "C" })))
.then(() => navigate(`/spectacles/${spectacles[spectacles.length - 1]?.id!}`));
}
});
};
Async thunk function to create the entry in the state1
export const createSpectacleAsync = createAsyncThunk<Spectacle, string>(
'artifices/createSpectacleAsync',
async (title: any, thunkAPI) => {
try {
return await agent.Spectacle.createSpectacle({ Titre: title });
} catch (error: any) {
return thunkAPI.rejectWithValue({error: error.data})
}
}
)
ExtraReducer to manage the new entry returned by the API
builder.addCase(createSpectacleAsync.fulfilled, (state, action) => {
spectacleAdapter.addOne(state, action.payload);
state.status = 'idle';
});