0

I have an issue about handeling rejected value. If I try to dispath function with a exist email and password everything is working, but when I enter the random email and password I can not reach the 404 error message which is coming from my backend.

This is my Slice Code

import { authService } from "../services/AuthService";

export const AuthSlice = createSlice({
  name: "weather",
  initialState: {
    authStatus: "idle",
    jwt: "",
    messageCode: "",
  },
  reducers: {},
  extraReducers: (builder) => {
    //Auth Controller
    builder
      .addCase(authService.pending, (state) => {
        state.authStatus = "loading";
      })
      .addCase(authService.fulfilled, (state, action) => {
        console.log("fullfiled", action);
        const {
          data: {
            code,
            message_code,
            result: { jwt },
          },
        } = action.payload;

        state.messageCode = message_code;
        state.jwt = jwt;
        state.authStatus = "succeeded";
      })
      .addCase(authService.rejected, (state, action) => {
        console.log("rejected", action.payload);
        state.authStatus = "failed";
      });
  },
});
export default AuthSlice.reducer;

This is Service Code

import axios from "axios";

export const authService = createAsyncThunk(
  "authController/auth",
  async (auth) => {
    const data = await axios({
      method: "post",
      url: "example.url",
      headers: {},
      data: {
        email: auth.email, 
        password: auth.password,
      },
    });
    return data;
  }
);

And these are the values coming from backend. if I enter random email and password the backend returns { "code": 0, "message": "User not found.", "message_code": "LOGIN_ERROR" }

if I enter exist email and password backend returns {code:1,message_code:"LOGIN_SUCCESS",result:jwt:"token here"}

the problem is when I enter the random value authService.rejected is running but nothing is come with action from service.

I tried to write catch after axios code but this time even if I get the error value from service it comes in to authService.fulfilled and this time code can not find jwt token normally and I get a new error thats why.

I want to know what is the optimum way to handle this problem. Is there any way to get error message coming from backend in authService.rejected or do I need to write catch and need to get error message in authService.fulfilled and write if control for jwt token error.

1 Answers1

0
    name: "contactDetails",
initialState: {
  contactInfoData: [],
  loading: false,
  error: null,
},
extraReducers: {
  [getContactsList.pending]: (state, action) => {
    state.loading = true;
  },
  [getContactsList.fulfilled]: (state, { payload }) => {
    state.loading = false;
    state.contactInfoData = payload;
  },
  [getContactsList.rejected]: (state, action) => {
    state.loading = false;
    state.error = action.payload;
  },
}

I hope this would be helpful