I created mern stack react application, using nodejs and express as a server. I want to recieve cookie with jwt token from the server and afterwards refresh the whole page completely and save the cookie. I tried to refresh the page by using window.location.reload(false) and also useHistory.get(0) but both of them refresh the page endless times till I deleted the token and then it stoped refreshing. I also tried to write window.stop() right after window.location.reload(false) but then it did not refresh the window at all. How an I refresh the whole window only once?
It is worth to mention that I don't have so much experience with react, so I would really appreciate your help. Thank you.
CodePudding user response:
React doesn't like when you refresh the page yourself. It prefers to handle that by itself. Using the useState
hook will auto-refresh the page when the state changes but you can also use the useEffect
hook to change the value without causing re-renders.
So what you might want to do is get the cookie, then use the setState
you created and the change of value will cause a refresh, while also storing the cookie.
CodePudding user response:
If you want to have the navbar and the page change based on login, you could just switch pages. So have one page where you login with one navbar, then, when logged in, change the page.
Heres an example for an easy way to switch between pages:
import {useState} from 'react';
import ReactDOM from 'react-dom/client';
function Index() {
const [login, setLogin] = useState(false)
if (login) {
return (
<div >
<h1> Logged in ! </h1>
</div>
)
} else {
return (
<div >
<button onClick={() => {
setLogin(true);
}>Login</button>
</div>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( <Index/> );
This re-renders everything on the page when swapping
It is probably better to do it in a format like this though: w3Schools Example with router