redux-promise with Axios, and how do deal with errors?

后端 未结 6 1653
梦如初夏
梦如初夏 2020-12-16 02:07

So, I see on an error, redux-promise hands me back error: true, along with the payload, but that is once it hits the reducer... to me, decoupling the request AND error condi

6条回答
  •  旧时难觅i
    2020-12-16 02:28

    It looks like you can catch the error where you make the dispatch, then make an separate error dispatch if it happens. It's a bit of a hack but it works.

      store.dispatch (function (dispatch) {
          dispatch ({
            type:'FOO',
            payload:axios.get(url)
          })
          .catch (function(err) {
            dispatch ({
              type:"FOO" + "_REJECTED",
              payload:err
            });
          });
      });
    

    and in the reducer

    const reducer = (state=initialState, action) => {
      switch (action.type) {
        case "FOO_PENDING": {
          return {...state, fetching: true};
        }
        case "FOO_REJECTED": {
          return {...state, fetching: false, error: action.payload};
        }
        case "FOO_FULFILLED": {
          return {
            ...state,
            fetching: false,
            fetched: true,
            data: action.payload,
          };
        }
      }
      return state;
    };
    

提交回复
热议问题