Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda