Reputation: 1273
I have a redux action which calls an api and returns an object. Profile object if it's performed successfully or error object if not. Everything works fine except one thing. I send the data through a modal window. If everything is ok, I just reload the page, if not, I don't want to reload the page, I want to display the errors. ACTION:
export const addEducation = (eduData, history) => dispatch => {
axios
.post("/api/profile/education", eduData)
.then(window.location.reload())
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
API:
router.post(
"/education",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validateEduInput(req.body);
//Check validation
if (!isValid) {
return res.status(400).json(errors);
}
Profile.findOne({ user: req.user.id }).then(profile => {
const newEdu = {
school: req.body.school,
degree: req.body.degree,
fieldOfStudy: req.body.fieldOfStudy,
from: req.body.from,
to: req.body.to,
current: req.body.current,
description: req.body.description
};
//Add to exp array
profile.education.unshift(newEdu); //Add the education to the beginning of the array opposed to push
profile
.save()
.then(profile => res.json(profile))
.catch(err => res.status(404).json(err));
});
}
);
As you can see in the API code, I validate the input received and return the errors object if it's not passing. Right now, the redux action reloads the page either way. How should I check if I have errors and prevent the page from reloading in the .then function?
Upvotes: 1
Views: 190
Reputation: 176
From the code, I couldn't decipher any error. Maybe, you can try binding the .then response as well:
then(() => window.location.reload())
Also, try debugging or logging the response to check for the status code in error case.
Upvotes: 1