Search code examples
reactjsreduxredux-toolkit

Redux-Toolkit createAsyncThunk function doesnt return error


I am using Redux Toolkit's createAsyncThunk function for api request. When turned off network, following function returns action.payload="Network Error" and status = "success". Status should be "error". But it returns success. Any suggestions to fix the problem ? Thanks in advance.

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

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

export const getPosts = createAsyncThunk("posts/getPostsStatus", async () => {
  try {
    const { data } = await axios.get(GET_POSTS_API);
    return data;
  } catch (error) {
    return error.response ? error.response.data.message : error.message;
  }
});

export const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {},
  extraReducers: {
    [getPosts.pending]: (state, action) => {
      state.status = "loading";
    },
    [getPosts.fulfilled]: (state, action) => {
      state.status = "success";
      state.posts = action.payload;
    },
    [getPosts.rejected]: (state, action) => {
      state.status = "error";
      state.error = action.payload;
    },
  },
});

export default postsSlice.reducer;

Solution

  • When you return a value, you are telling createAsyncThunk that this is a successfully fulfilled request, and the returned value becomes action.payload.

    If you skip catching errors entirely and just let the axios.get() call throw and reject the promise itself, it will correctly dispatch a rejected action.

    If you want the result of the thunk to be considered rejected, but you want to customize what the contents of the action are, you need to use the rejectWithValue() util as shown in in our docs:

    https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-errors