Answer the question
In order to leave comments, you need to log in
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))
}
}
Answer the question
In order to leave comments, you need to log in
In the plan, they should be passed to the reducer for errors, and in the component, monitor the change in this reducer ...
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;
}
}
const mapStateToProps = state => ({
error: loginErrorSelector(state),
});
render() {
const { error } = this.props;
if (error) return <TryAgain error={error} action={login} />;
return ( /* ... */ );
}
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 questionAsk a Question
731 491 924 answers to any question