svrcekmichal / redux-axios-middleware

Redux middleware for fetching data with axios HTTP client
MIT License
918 stars 96 forks source link

Improve Documentation (example) #60

Closed acmitch closed 7 years ago

acmitch commented 7 years ago

I'm struggling to understand the correct way to utilize this library. If I need to parse the returned response and do any sort of extraction/validation ... it seems, I have to handle response logic within the reducers (which doesn't seem right)? Moreover, I notice there are onSuccess/onError functions but no documentation on how or where to define and whether or not they are global on every request or per request (are they part of the middleware config or action). Overall, this needs improved documentation, is there any example application that utilizes this library so I can see if this fits the teams needs or whether to create our own middleware for handling request headers and JWT tokens?

nmaves commented 7 years ago

First off, there is nothing wrong with working on the response data in a reducer. If you really wanted to take care of this outside(before) your reducers you could capture the response in a .then() on your action creator and then dispatch again after the data cleanup but this just sounds messy to me.

To your question on headers (auth) I would check out our integration to axios interceptors. That is how we use them in production.

acmitch commented 7 years ago

Currently, this is what I have when signing in a user. However, parsing the many combinations of responses seems a little messy. Is there a recommended/better way of handling the responses, specifically error responses? This is why I didn't want to place the code inside the reducers.

Note: This is with returnRejectedPromiseOnError set to true.

export function signInUser(creds) {
  return dispatch => {
    return dispatch(getAccessToken(creds))
      .catch(response => {

        let message = "";

        if(response.error.status === 0){
          message = response.error.data;
        }else{
          message = response.error.response.data.message;
        }

        dispatch(loginUserFailure(message));

        return Promise.reject(new Error(message));
      })
      .then(response => {
        let message = response.payload.data.access_token;

        dispatch(loginUserSuccess(message));
      });
  }
}

export function getAccessToken(creds) {
  return {
    type: 'AUTH_REQUEST',
    payload: {
      request: {
        url: '/oauth/token',
        method: 'POST',
        data: {
          'grant_type': 'password',
          'client_id': 'fadfa',
          'client_secret': 'dfaafa',
          "username": creds.username,
          "password": creds.password,
          'scope': '*'
        }
      }
    }
  }
}
nmaves commented 7 years ago

That looks great to me!

I don't see any issues with that code.