Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

reactjs - Redux Toolkit: Unable to get access to the error message sent from the server

I have a Products component, that makes a GET request to '/api/products'. At the backend, in the route handler function, I am throwing an error & sending a custom error message ('Not Authorized') to the client.
enter image description here

At client side, I want to display the custom error message that I have sent from the server. However, when I console.log the action object, the error message reads: 'Request Failed with status code 500'. enter image description here

How can I get access to the error message that I send back from the server?

I did some research for handling error in createAsyncThunk. As per the documentation, I can handle errors with rejectWithValue.But I couldn't figure out how to implement that in my case.

Code snippets are given below:

productsSlice.js

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
  status: "idle",
  products: [],
  error: null,
};

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts",
  async () => {
    const { data } = await axios.get("/api/products");
    return data;
  }
);

export const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.fulfilled]: (state, action) => {
      state.status = "succeeded";
      state.products = action.payload;
    },
    [fetchProducts.pending]: (state, action) => {
      state.status = "loading";
    },
    [fetchProducts.rejected]: (state, action) => {
      console.log(action);
      state.status = "failed";
      state.error = action.error.message;
    },
  },
});

export default productsSlice.reducer;

Products.js

import React, { useEffect } from "react";
import { Row, Col } from "react-bootstrap";
import Product from "./Product";
import { fetchProducts } from "./productsSlice";
import { useDispatch, useSelector } from "react-redux";

const Products = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchProducts());
  }, [dispatch]);

  const { status, products, error } = useSelector((state) => state.products);

  return (
    <>
      <h1>Latest Products</h1>
      {status === "loading" ? (
        <h2>Loading...</h2>
      ) : error ? (
        <h3>{error}</h3>
      ) : (
        <Row>
          {products.map((product) => (
            <Col sm={12} md={6} lg={4} xl={3} key={product._id}>
              <Product item={product} />
            </Col>
          ))}
        </Row>
      )}
    </>
  );
};

export default Products;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I finally managed to get access to the error message sent from the server using rejectWithValue utility function.

Doing return rejectWithValue(errorPayload) causes the rejected action to use that value as action.payload.

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
  status: "idle",
  products: [],
  error: null,
};

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts",
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axios.get("/api/products");
      return data;
    } catch (err) {
      return rejectWithValue(err.response.data);
    }
  }
);

export const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.fulfilled]: (state, action) => {
      state.status = "succeeded";
      state.products = action.payload;
    },
    [fetchProducts.pending]: (state, action) => {
      state.status = "loading";
    },
    [fetchProducts.rejected]: (state, action) => {
      console.log(action);
      state.status = "failed";
      state.error = action.payload.message;
    },
  },
});

export default productsSlice.reducer;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...