I have two reducers: errorReducer
and userReducer
.
I have a login
action:
export const login = (login) => (dispatch) => {
axios.post("http://localhost:5000/login", login).then((res) => {
if (res.data.token) {
localStorage.setItem("token", res.data.token);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
dispatch({
type: CLEAR_ERROR,
});
} else if (res.data.status === "Invalid credentials.") {
dispatch({
type: ERROR,
payload: res.data.status,
});
}
});
};
As you can see, if the login fails, there is an error. An error message appears for the user. However, if the login is successful, then I need to clear the error state with another dispatch. Is this a good practice? If I don't do this, then the error will stay in the state and that's not good I guess.
And if I login successfully for the first try, the CLEAR_ERROR
runs too, I don't want that.
How can I reset the ERROR
case in the login
action without dispatching?
I am planning to make a loadingReducer as well, but then I will need to dispatch that too. Isn't that too many? Is there a way around this? I could put error and loading in the userReducer, but I'm not sure if that's a good practice either.
errorReducer:
import { ERROR, CLEAR_ERROR } from "../actions/types";
const initialState = [];
export default function (state = initialState, action) {
switch (action.type) {
case ERROR:
return action.payload;
case CLEAR_ERROR:
return [];
default:
return state;
}
}
userReducer:
import { LOGIN_SUCCESS } from "../actions/types";
const initialState = {
user: {},
authenticated: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case LOGIN_SUCCESS:
return {
...state,
loading: false,
authenticated: true,
...action.payload,
};
default:
return state;
}
}
I would use an effect to show an error message in a toaster for example. Not storing it in the state.
If you do want to keep it in the state then you could state that a successful login implies that the error should be empty. So you could handle that in the LOGIN_SUCCESS case.
Your states in both reducers do not match though. They should be the same object. So make a file somewhere that exports the initialState and use that in both reducers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.