Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda