简体   繁体   English

如何使用 redux 工具包和 typescript 为登录创建 AsyncThunk

[英]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.

相关问题 Redux 工具包使用 createAsyncThunk 和 typescript 错误处理 - Redux toolkit using createAsyncThunk and typescript error handling 如何在 createAsyncThunk 上访问 Redux Toolkit 上的当前状态 - How to access current state on Redux Toolkit on createAsyncThunk 如何通过 Redux Toolkit 和 createAsyncThunk 使用 firebase 身份验证? - How to use firebase authentication with Redux Toolkit and createAsyncThunk? 带有 Typescript 的 Redux-Toolkit。无法分派由 createAsyncThunk 创建的操作 - Redux-Toolkit with Typescript. Cannot dispatch action created by createAsyncThunk 带有 typescript rejecWithValue 和有效负载类型错误的 createAsyncThunk redux 工具包 - createAsyncThunk redux toolkit with typescript rejecWithValue and Payload types error 当 createAsyncThunk 返回 promise 时如何更新组件(react/redux 工具包) - How update the component when the createAsyncThunk return a promise (react/redux toolkit) redux工具包中如何将arguments传递给createAsyncThunk? - How do you pass arguments to createAsyncThunk in redux toolkit? 如何从 React 组件 Redux Toolkit 中的 createAsyncThunk 获取结果 - How to get result from createAsyncThunk in React component Redux Toolkit 无法使用 createAsyncThunk 更新 redux-toolkit 中的initalState - cannot update initalState in redux-toolkit with createAsyncThunk redux-toolkit 在 createAsyncThunk 中获取很多数据 - redux-toolkit fetch many data in createAsyncThunk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM