Home > Blockchain >  How to show reject message with createAsyncThunk?
How to show reject message with createAsyncThunk?

Time:11-26

I want to show an error message when my API fetch throws an error but this error actually gets fulfilled so in the extra reducers, the rejected part doesn't get invoked at all.

    export const searchWeather = createAsyncThunk(
      "weather/searchWeather",
      async (apiAddress) => {
        const response = await fetch(apiAddress);
        const data = await response.json();
        return data;
      }
    );

................................................................................

      extraReducers: (builder) => {
        builder
          .addCase(searchWeather.pending, (state) => {
            state.isLoading = true;
            state.hasError = false;
          })
          .addCase(searchWeather.fulfilled, (state, action) => {
            state.weather = action.payload;
            state.isLoading = false;
            state.hasError = false;
          })
          .addCase(searchWeather.rejected, (state) => {
            state.isLoading = false;
            state.hasError = true;
          });
      },

In this way even if I get a 404 Error, it still does get fulfilled and not rejected.

What I did was to include Promise.reject() in my async function in this way:

export const searchWeather = createAsyncThunk(
  "weather/searchWeather",
  async (apiAddress) => {
    const response = await fetch(apiAddress);
    if (!response.ok) {
        return Promise.reject();
      }
    const data = await response.json();
    return data;
  }
);

And it indeed does work without any problems and shows the error message I've defined somewhere else.

But I want to know if this is actually the right way to do it or if there is a better solution to this.

CodePudding user response:

This is pretty much the correct way - fetch does not throw on a non-2xx-status code.

Sementics can change a bit - you would usually either throw or return rejectWithValue:

    if (!response.ok) {
        throw new Error("response was not ok")
      }

or

    if (!response.ok) {
        return thunkApi.rejectWithValue("response was not okay")
     }
  • Related