K
K
Knyashshsh2019-03-26 10:36:29
React
Knyashshsh, 2019-03-26 10:36:29

Redux request state management options?

export const authLogin = userData => async dispatch => {
    dispatch(fetchPending())

    try {
      const { token } = await ApiService.post('/api/users/login', userData)

      setAuthToken(token)
      await dispatch(setCurrentUser(decodeJwt(token)))

      history.push("/")
    } catch(err) {
      dispatch(fetchFailed(err.response.errors))
    }
}

This is how I mostly write actions, but the question is, are there even more concise ways to process the request state?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-03-26
@fyapy

In the plan, they should be passed to the reducer for errors, and in the component, monitor the change in this reducer ...

No need. The error and loading status can be handled in the same reducer as the token.
const initialState = {
  isFetching: false,
  token: null,
  error: null,
};

function auth(initialState, action) {
  switch(action.type) {
    case LOGIN_REQUEST:
      return {
        ...state,
        isFetching: true,
        error: null,
      };

    case LOGIN_SUCCEEDED:
      return {
        ...state,
        isFetching: false,
        token: action.payload,
      };

    case LOGIN_FAILED:
      return {
        ...state,
        isFetching: false,
        error: action.payload,
      };

    default:
      return state;
  }
}

Will not.
It is not clear why you would add an error to state.
const mapStateToProps = state => ({
  error: loginErrorSelector(state),
});

render() {
  const { error } = this.props;

  if (error) return <TryAgain error={error} action={login} />;
  
  return ( /* ... */ );
}

A
Andrey Gurtovoy, 2019-03-27
@jt3k

Anton Spirin set an excellent example. It is worth adding that it is convenient to create these actions through a special middleware - promise-middleware. In which you will pass only the LOGIN keyword and the request promise itself, and at the output you will receive a call to the reducers, as Anton described

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question