Context : I want to set in Redux store the response from my API when the user logs in.
For that, i use createAsyncThunk
as the documentation says.
Problem: With my code, I get the following error :
Argument of type 'AsyncThunkAction<any, { email: string; password: string; }, AsyncThunkConfig>' is not assignable to parameter of type 'AnyAction'
How can I solve this ?
Here is my code :
My code : loginSlice.ts
export const loginUser = createAsyncThunk("LOGIN", async (data: { email: string; password: string }) => {
const response = await Logs.login(data.email, data.password);
console.log("response", response);
return response.data;
});
const loginSlice = createSlice({
[...]
extraReducers: (builder) => {
builder.addCase(loginUser.pending, (state, action) => {
state.loading = true;
});
builder.addCase(loginUser.fulfilled, (state, action) => {
state.loading = false;
state.data = action.payload;
});
builder.addCase(loginUser.rejected, (state, action) => {
state.loading = false;
console.log("state", state);
console.log("action", action);
});
},
});
export const loginReducer = loginSlice.reducer;
Login.tsx
[...]
const onSubmit: SubmitHandler<ILoginData> = (data) => {
dispatch(loginUser(data));
};
[...]
PS : data
is just an object with email
and password
from the form.
CodePudding user response:
The issue is that the default Redux Dispatch
type does not know about thunks, because they are an optional middleware that extends the store's behavior.
That's why we specifically direct users to infer an AppDispatch
type based on the actual store setup, and use "pre-typed" React hooks that have the store types baked in. That way your components have the correct types for usage situations like this:
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector