Umut Palabiyik
Umut Palabiyik

Reputation: 323

i cant catch status and json values from createAsyncThunk function

usersSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { API } from "../axios/index";

export const signUp = ...

export const logOut = ...

export const signIn = createAsyncThunk("users/signin", async (params) => {
  try {
    const { loginData, history } = params;
    const { data } = await API.post("users/signin", loginData);
    history.push("/");
    return data;
  } catch (error) {
    console.log(error);
  }
});

const initialState = {
  usersInfo: {},
  status: "idle",
  error: null,
  existEmail: false,
};

const usersSlice = createSlice({
  name: "users",
  initialState,
  reducers: {
    handleExistEmail: (state, action) => {
      state.existEmail = action.payload;
    },
  },
  extraReducers: {
     ...
    [signIn.fulfilled]: (state, action) => {
      console.log("here is your data : ", action.payload);
      state.status = "succeeded";
      if (action.payload) {
        localStorage.setItem("user", JSON.stringify(action.payload));
      }
    },
  },
});

export default usersSlice.reducer;
export const { handleExistEmail } = usersSlice.actions;

userRouter.js

const isPasswordCorrent = await bcrypt.compare(password, user.password);

if (!isPasswordCorrent) {
  return res
    .status(404)
    .json({ message: "Password dont match" });
}

Hi all.When password and re-passwordn dont match i want to backend send me status(404) and json({ message: "Password dont match" }) values and i want to catch these values in [signIn.fulfilled] but action.payload send me undefined.But if i do return res.json({ message: "Password dont match" }) instead of return.status(404).json({message: "Password dont match"}) this time i cant catch json({message: "Password dont match"}) from [signIn.fulfilled].Why i have to delete .status(404) part to dont get undefined ?

Upvotes: 0

Views: 178

Answers (1)

Anarno
Anarno

Reputation: 1640

This is how the createAsyncThunk works. This wrapper itself is a try/catch block, so doesn't make sense to use in this action creator function. If a promise is rejected in this creator function body, then your action returns a rejected sub-action in the store. So you have to listen to this action in the reducer. Or if you really want to use a try/catch block, then in the catch block throw the error. A little example usage:

export const exampleAsyncAction = createAsyncThunk(
  ACTION_TYPE,
  async (parameter) => {
    const result = await apicall(parameter);
    return result.doSomeLogic();
  }
);

const reducer = createReducer(
...,

[exampleAsyncAction.pending]: (state) => {
  state.loading = true;
  state.error = null;
},
[exampleAsyncAction.fulfilled]: (state, {payload}) => {
  state.result = payload;
  state.loading = false;
},
[exampleAsyncAction.rejected]: (state, {error}) => {
  state.error = error;
  state.loading = false;
},
)

Upvotes: 1

Related Questions