Estoy haciendo una llamada de despacho múltiple en la página de inicio
Era algo como esto.
useEffect(() => { async function getStorageData() { setLoading(true); try { await dispatch(fetchProductA()); await dispatch(fetchProductB()); await dispatch(fetchProductC()); await dispatch(fetchProductD()); await dispatch(fetchProductE()); } catch (err) { console.log(err); } finally { setLoading(false); } } getStorageData(); }, []);El problema es que al llamar a estos api. Recibí un error cuando productC. Así que hice una llamada de despacho.
Intento arrojar un error, pero eso no funciona porque cuando arroja un error en el producto C, el producto restante D y E no se llamarán porque arrojan el final de la llamada de despacho.
Aquí está mi llamada api.
export const fetchProductC = () => dispatch => { return axios .get('productsapi/fetchProductC', { headers: { 'Content-Type': 'application/json', }, }) .then(res => { dispatch({ type: FETCH_NEW_PRODUCTS, payload: res.data[0] }); }) .catch(err => { dispatch({ type: EMPTY_NEW_PRODUCTS, }); console.log('fetching new product error'); //throw err; }); };aqui esta el reductor
case FETCH_NEW_PRODUCTS: return { ...state, listC: action.payload, }; case EMPTY_NEW_PRODUCTS: return { ...state, listC: [], };Su código después de ProductC no se puede ejecutar porque se omite a través de catch.
Puede escribir su código como se muestra a continuación.
await dispatch(fetchProductA()).catch(handleErr); await dispatch(fetchProductB()).catch(handleErr); await dispatch(fetchProductC()).catch(handleErr); await dispatch(fetchProductD()).catch(handleErr); await dispatch(fetchProductE()).catch(handleErr);Nunca debe esperar un despacho en el componente. Lea tutoriales y refactorice su flujo de datos: Redux Async Data Flow , Async Logic y Data Fetching
Redux te recomienda usar thunk para hacer esto:
// fetchTodoById is the "thunk action creator" export function fetchTodoById(todoId) { // fetchTodoByIdThunk is the "thunk function" return async function fetchTodosThunk(dispatch, getState) { // dispatch an action to set a loading state dispatch(/*...*/) const response = await client.get(`/fakeApi/todo/${todoId}`) // use your response and set a success state here dispatch(todosLoaded(response.todos)) } } // Your component function TodoComponent({ todoId }) { const dispatch = useDispatch() const { data, state } = useSelector(/* your selector */) const onFetchClicked = () => { // Calls the thunk action creator, and passes the thunk function to dispatch dispatch(fetchTodoById(todoId)) } }