Where to make requests to the API?

Example Acton'and
// Login - Get User Token
export const loginUser = (userData, 'history') = > dispatch => {
axios
 .post("/api/users/login", userData)
 .then(res => {
 // Save to localStorage
 const { token } = res.data;
 // Set token to ls
 localStorage.setItem("jwtToken", token);
 // Set the Auth token to the header
setAuthToken(token);
 // Decode the token to get user data
 const decoded = jwt_decode(token);
 // Set current user
dispatch(setCurrentUser(decoded));

history.push("/");
})
 .catch(err => {
dispatch({
 type: SET_LOGIN_ERRORS,
 payload: err.response.data.errors
});
});
};

If they do in action how to handle errors normal? In terms so they must be passed in reducer for errors, and the component to watch for changes that reducer...
Is it right to make requests from the component? It is so in case of mistake we can immediately add in state component errors and all. Just the Internet is constantly see the queries in action, but it is not convenient or I don't understand.
March 19th 20 at 08:36
2 answers
March 19th 20 at 08:38
Solution
In terms so they must be passed in reducer for errors, and the component to watch for changes that reducer...

It is not necessary. Error and the download status can be treated in the same reducer that 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: the action.payload,
};

default:
 return state;
}
}


Is it right to make requests from the component?

Will not.

It is so in case of mistake we can immediately add in state component errors and all.

It is not clear why do you add error to state.

const mapStateToProps = state => ({
 error: loginErrorSelector(state),
});


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

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

 return ( /* ... */ );
}
March 19th 20 at 08:40
Anton Spirin, a great example showed. I should add that it is convenient to create the data action through a special middle - promise middleware. You'll give only the keyword LOGIN and the promis request, and the output will have the challenge of reduceron as described by Anton

Find more questions by tags ReduxReact