Home > front end >  Show errors received by Laravel in async actions Redux toolkit
Show errors received by Laravel in async actions Redux toolkit

Time:09-13

This is the async thunk function in my slice, I'm using axios (http is coming from another file defined as axios.create())

export const loginUser = createAsyncThunk("auth/fetchUsers", async (data) => {
  const response = await http.post("/login", data);
  return response.data;
});

In above data is an object passed through dispatch method (data contains email and password).

This is my initial state,

const initialState = {
    loading: false,
    user: [],
    error: [],
  },

This is my reducer, I use extra reducers So I can stage the above loginUser into stages as pending,fullfilled,rejected

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
  },
  extraReducers: (builder) => {
    builder.addCase(loginUser.pending, (state) => {
      state.apiHandler.loading = true;
    });
    builder.addCase(loginUser.fulfilled, (state, action) => {
      state.apiHandler.loading = false;
      state.apiHandler.user = action.payload;
      state.apiHandler.error = [];
    });
    builder.addCase(loginUser.rejected, (state, action) => {
      state.apiHandler.loading = false;
      state.apiHandler.user = [];
      state.apiHandler.error = action.error.message;
    });
  },
});

I'm trying to get the exact error messages returning from Laravel. But I'm getting the message as Request failed with status code 422 in the rejected cycle.With postman I'm retrieving the exact error,

{
    "message": "Incorrect Credentials"
}

This is a potion of my Laravel code, (So if something is not fullfilled it should return errors),

$request->validate([
  'email'    => 'required | exists:users',
  'password' => 'required'
]);

My question is: How to retrieve the exact error messages with asyncThunk reject method without retrieving Request failed with status code 422 as the error.

CodePudding user response:

I don't know about your project structure. However, you can actually get the Laravel errors, by waiting for a json response and accessing response's .errors .

For Example:

if (response. Status === 422) {
    const validation = await response.json();
    this.message= validation.errors
    this.error= true;
}

According to your project structure, place this logic in your responses, anywhere suitable.

What I see here is you return response.data anyways, while laravel errors reside in response.errors object.

I hope it helps.

CodePudding user response:

I attached try catch and passed the 2nd argument as {rejectWithValue} for the createAsyncThunk, and catching the errors with action.payload in case.rejected ,

export const loginUser = createAsyncThunk(
  "auth/fetchUsers",
  async (payload, { rejectWithValue }) => {
    try {
      const { data } = await http.post("/login", payload);
      return data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

extraReducers: (builder) => {
   ...
    builder.addCase(loginUser.rejected, (state, action) => {
      state.loading = false;
      state.user = [];
      state.error = action.payload;
    });
  },
  • Related