简体   繁体   中英

How to createAsyncThunk for signIn with redux toolkit with typescript

I have problem with implementing login method on React by using reduxjs/toolkit. The biggest problem for me is integrating it with typescript.

User must fill email and password fields. Then click login. My thunk must recieve these two fields and should log user with JWT token saved on localStorage.

From my API i will recieve data like this:

{
    "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 :

export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM