[英]How to createAsyncThunk for signIn with redux toolkit with typescript
I have problem with implementing login method on React by using reduxjs/toolkit.我在使用 reduxjs/toolkit 在 React 上实现登录方法时遇到问题。 The biggest problem for me is integrating it with typescript.
对我来说最大的问题是将它与 typescript 集成。
User must fill email and password fields.用户必须填写 email 和密码字段。 Then click login.
然后点击登录。 My thunk must recieve these two fields and should log user with JWT token saved on localStorage.
我的 thunk 必须收到这两个字段,并且应该使用保存在 localStorage 上的 JWT 令牌记录用户。
From my API i will recieve data like this:从我的 API 我会收到这样的数据:
{
"status": "success",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxY2M2Yjc5ZTRiMmU0OWE1OGZlZDViZiIsImlhdCI6MTY0MTU2NDAxNSwiZXhwIjoxNjQ5MzQwMDE1fQ.Yr6RxB6q1TvLeOjy2fg1pZ9kvXpA2lgV8cW4G67lJnc",
"data": {
"data": {
"role": "user",
"_id": "61cc6b79e4b2e49a58fed5bf",
"name": "user1",
"email": "user1@gmail.com",
"passwordChangedAt": "2021-12-29T14:06:48.771Z",
"__v": 0,
"id": "61cc6b79e4b2e49a58fed5bf"
}
}
}
My code:我的代码:
export const signIn = createAsyncThunk(
'auth/signIn',
async ({ email, password }: { email: string; password: string }, thunkAPI) => {
try {
const response: {
status: any;
token: string;
data: {
data: {
name: string;
};
};
} = await api.post('/auth', {
email,
password,
});
console.log('response', response);
if (response.status === 200) {
localStorage.setItem('token', response.token);
return response;
} else {
return thunkAPI.rejectWithValue(response.data);
}
} catch (e) {
console.log('Error', e);
return thunkAPI.rejectWithValue(e);
}
}
);
export const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {},
extraReducers: builder => {
builder.addCase(signIn.pending, state => {
state.isFetching = true;
});
builder.addCase(signIn.fulfilled, (state, action) => {
state.isFetching = false;
state.currentUser = action.payload;
});
builder.addCase(signIn.rejected, (state, action) => {
state.isFetching = false;
state.errorMessage = action.error.message;
// state.errorMessage = action.payload;
});
},
});
When i execute this method like this:当我像这样执行此方法时:
dispatch(signIn(values));
I'm getting this error:我收到此错误:
(alias) signIn(arg: {
email: string;
password: string;
}): AsyncThunkAction<unknown, {
email: string;
password: string;
}, {}>
import signIn
Argument of type 'AsyncThunkAction<unknown, { email: string; password: string; }, {}>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'AsyncThunkAction<unknown, { email: string; password: string; }, {}>' but required in type 'AnyAction'.ts(2345)
Could you help me fix this?你能帮我解决这个问题吗?
Your dispatch does not know about your store types.您的调度不知道您的商店类型。 Set up
useDispatch
as described in the TypeScript QuickStart :按照TypeScript 快速入门中的说明设置 useDispatch
useDispatch
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.