i am using latest version of react and react router dom v 6
i am developing registration system and after successful registration want to navigate to login. but history.push is not working in redux action page
here is code
history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory({ forceRefresh: true });
authSlice.js
import history from "../../history";
export const register = (user) => async (dispatch) => {
try {
const userData = {
username: user.username,
email: user.email,
contact: user.contact,
password: user.password,
};
const response = await axios.post(
"http://localhost:4000/auth/register",
userData
);
if (response) {
// console.log("data is ", response.data);
dispatch(registerSuccess(response.data));
toast.success("Registration Successful. You can now login");
history.push("/signin");
} else {
console.log("error");
dispatch(registerFailure());
toast.error("registration failed");
}
} catch (error) {
if (error.response.status === 400) toast.error(error.response.data);
dispatch(registerFailure());
}
};
though user is getting registered in db and url also changing but not the view
CodePudding user response:
I was also searching for the same answer but failed to find one that worked, ended up using window.location.reload()
as a fix.
CodePudding user response:
You should use <Router>
in route file to synchronize it with react-router.
CodePudding user response:
If you getting issue in using history so you can use useHistoy() hook instead of createBrowserHistory or you can use withRouter()
Like
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
const register = (user) => async (dispatch) => {
const { match, location, history } = user;
try {
const userData = {
username: user.username,
email: user.email,
contact: user.contact,
password: user.password,
};
const response = await axios.post(
"http://localhost:4000/auth/register",
userData
);
if (response) {
// console.log("data is ", response.data);
dispatch(registerSuccess(response.data));
toast.success("Registration Successful. You can now login");
history.push("/signin");
} else {
console.log("error");
dispatch(registerFailure());
toast.error("registration failed");
}
} catch (error) {
if (error.response.status === 400) toast.error(error.response.data);
dispatch(registerFailure());
}
}
export default withRouter(register);