0

So I created async Thunk function, and in try{}catch{} block I recieve error, and then with method rejectwithvalue I send it to extraReducer, rejected case. I do recieve it, I can console.log(action.payload), yet I cannot assign payload value to state.error due to error: error:

enter image description here

import { createSlice,PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import axios from "axios";
import { User } from '../../types/User';
import { FormSignUp } from '../../types/FormSignUP';

type InitialState = {
  user: User | null;
  status:'idle' | 'failed' | 'pending' | 'fullfilled';
  error: string | null;
};

const initialState: InitialState = {
  user: null,
  status: 'idle',
  error: null,
};

export const signupUser = createAsyncThunk('user/signupUser', async (user: FormSignUp, thunkAPI) => {
  try {
    const response = await axios.post(API_URL, user);
    return response.data
  } catch (err) {
    if (axios.isAxiosError(err)) {
      if (
        err.response
        && err.response.data
        && err.response.data.error
      ) {
        console.log(err)
        return thunkAPI.rejectWithValue(err.response.data.error);
      } else {
        return thunkAPI.rejectWithValue(err.message)
      }
    }
  }
});

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(signupUser.rejected, (state, action) => {
        if (action.payload) {
          state.error = action.payload;
        }
        console.log(action.payload)
        state.status = 'failed';
        state.error = 'error';
      });
  },
});

Payload is basicly a string, but when I add string type to payload:

.addCase(signupUser.rejected, (state, action: PayloadAction<string>) => {
        if (action.payload) {
          state.error = action.payload;
        }

I have even worse error: TS2769: No overload matches this call. Overload 1 of 2, '(actionCreator: AsyncThunkRejectedActionCreator<FormSignUp, {}>, reducer: CaseReducer<InitialState, PayloadAction<unknown, string, { arg: FormSignUp; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ ...; } | ({ ...; } & {})), SerializedError>>): ActionReducerMapBuilder<...>', gave the following error.................

Edited:

This helped, now code is working. I made sure that string will be as an argument of rejectWithValue method.

      return thunkAPI.rejectWithValue(`${err.response.data.error}`);

in addCase I made type check of recieved payload.

.addCase(signupUser.rejected, (state, action ) => {
        if (typeof action.payload === 'string') {
          state.error = action.payload;
        }
Paul Gutsal
  • 107
  • 2
  • 12

0 Answers0