如果axios请求失败,如何将错误置于状态?Redux工具包

5uzkadbs  于 2022-11-12  发布在  iOS
关注(0)|答案(1)|浏览(129)

我正在做一个简单的电子商务应用程序,我想展示所有的产品。我使用redux工具包,根据文档,我找不到任何地方如何处理错误。这是我的产品切片:

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

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

const initialState = {
  loading: false,
  products: [],
  product: {},
  error: '',
};

export const productsSlice = createSlice({
  name: 'products',
  initialState,
  reducers: {},
  extraReducers: {
    [getProducts.pending]: state => {
      state.loading = true;
    },
    [getProducts.fulfilled]: (state, { payload }) => {
      state.loading = false;
      state.products = payload;
    },
    [getProducts.rejected]: (state, { payload }) => {
      state.loading = false;
      state.error = payload;
    },
  },
});

export const productsReducer = productsSlice.reducer;
ego6inou

ego6inou1#

[getProducts.rejected]: (state, { error }) => {
      state.loading = false;
      state.error = error.message;
    }

相关问题