When fetchUserById()
is created its output response is defined.
const fetchUserById = createAsyncThunk<{user: UserInterface, id: number}, number>(
'users/fetchByIdStatus',
async (userId) => {
const response = await userAPI.fetchById(userId)
return {user: response.data, id: userId}
}
);
const userSlice = createSlice({
name: "users",
initialState: [],
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchUserById.pending, (state, { payload }) => {
// how I configured custom value for this payload?
// I need to send the user id.
});
builder.addCase(fetchUserById.fulfilled, (state, {payload}) => {
/**
* @var {UserInterface} user
* @var {number} id;
*/
const {id, user} = payload;
state[id].loading = false;
state[id].user = user;
});
},
});
But how can I define a response when the action is on "pending" state?
The arg that you pass into createAsyncThunk
will be available in action.meta.arg
. So in your example, you could reference that like this:
builder.addCase(fetchUserById.pending, (state, { meta }) => {
console.log(meta.arg); // meta.arg will have whatever value was passed as `userId`
});