'/'URL Login handler function
const loginHandler = (e) => {
e.preventDefault();
Services.login(email, password)
.then((Res) => {
if(Res.data==="success"){
navigate('/home')
}
else {
navigate('/',{
state: {
msg: Res.data,
}})
}
})
.catch((error) => {
console.log(error);
});
};
On Res.data other than success I want to redirect to the same /Url by updating the state of a component so that I can display proper error message on the same page and prevent user to navigate to /home Url . How can I do that?
I think you'll find it's not too useful to navigate to the same page as you intend. Seems more straightforward to keep some state on the current page and show/hide an error message based on that state
import React, { useState } from 'react';
const ThisPage = () => {
const [failed, setFailed] = useState(false);
const loginHandler = () => {
....when you get to your error
}else{
setFailed(true);
}
}
//then render an error message on this page if failed
return(
<div>
<SomeOtherContent />
<div hidden={!failed}>Something went wrong!</div>
</div>
);
}
If you really need to navigate to the same page, you could look into using useContext() to keep a state that is outside of the page component so that it would still be there when you redirect to the same component (and rerender it). https://reactjs.org/docs/hooks-reference.html#usecontext