Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
How to show reject message with createAsyncThunk?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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")
     }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!