Chaining dispatch from react not stop if there are errors

Viewed 29

i have this code:

const deleteResponse = () => {   
    if (estado === 'new'){      
      dispatch(deleteNewResponse(id))
        .then(() => {        
          dispatch(deleteNewVariations({id: id, token: token}))            
            .then(() => { 
              dispatch(deleteNodeWatson(id));
            }); 
        });       
      retId(id);      
      
    } else { 
      retId(id);
      console.log('borrando respuesta de produccion');
    }
  };

This is my slice.js:

export const deleteNewVariations = createAsyncThunk (
  "delte-new-variations/delete",
  async (variationsData) => {    
    const { id, token } = variationsData;
    try { 
      const res = await FaqsService.deleteNewVariations(id, token);   
      console.log(res);    
      return res.data;
    } catch (error) {
      console.log(error.request.status);
      return error.request.status;
    }
  });

This are inside extrareducers:

[deleteNewVariations.rejected]:(state, action) => {  
      console.log(action.payload);
      state.error = action.payload;
    },
    [deleteNewVariations.fulfilled]:(state, action) => {  
      console.log(action.payload);
      state.error = action.payload;
    }

With this code, i try to delete the information that is in my database, in three different tables.

The function deleteResponse() works always.

I try to create an error to stop the function (deleted some row manually before launch the function) just in the error. And in my console i see the error (404) that i have prepared in my backend.

But the function doesn't stop and finish the chain and remove the rows in the database.

I don't know how to complete my then() to stop the funcion when second or third dispatch fails.

Thanks

1 Answers

As mentioned in this response, a 404 response is still a valid response so the dispatch() function will still trigger the .then() callback. To solve this issue just check that the request response status code is a 2xx something:

const deleteResponse = () => {
  if (estado === 'new') {
    dispatch(deleteNewResponse(id))
      .then((deleteNewRes) => {
        if (deleteNewRes.ok) {
          dispatch(deleteNewVariations({
              id: id,
              token: token
            }))
            .then((deleteVariationsRes) => {
              if (deleteVariationsRes.ok) dispatch(deleteNodeWatson(id))
            });
        }
      });
    retId(id);

  } else {
    retId(id);
    console.log('borrando respuesta de produccion');
  }
};
Related