I'm encountering this error in my Next.js application:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Inside my Navbar component, there's an li tag that is rendered conditionally based on whether the user is logged in or not. I suspect this line is causing the error because removing it resolves the issue. How can I perform this conditional rendering without triggering the error?
const token = cookies.token;
const usuario = cookies.usuario;
<ul className="navbar-nav">
<li className="nav-item">
<a href="/about" className="link">About us</a>
</li>
<li className="nav-item">
<a href="/about" className="link">Team</a>
</li>
<li className="nav-item">
<a href="/about" className="link">Articles</a>
</li>
{token ? (
<li className="nav-item">
<a href="/about" className="link">Hello, {usuario.nome}</a>
</a>
</li>
) : null}
</ul>
EDIT: Actually, now I've discovered that the error occurs when I try to retrieve cookies.token and cookies.usuario from the context. I'm using useContext from React. I've attempted to use useEffect, but it's not retrieving the values
const { cookies } = useContext(AuthContext);
var token = "";
var userData = { nome: "" };
useEffect(() => {
token = cookies.AdvWebsite;
userData = cookies.UserData;
}, []);
EDIT: I also attempted to use states instead of vars, but the username did not update to display on the screen. I could resolve this issue importing dynamic from "next/dynamic" in the file and exported the function as follows:
export default dynamic (() => Promise.resolve(Navbar), {ssr: false})
First it would informative to see how does the
cookiesresolve. Another thing, you might try to assign a state variable for the token and just get the cookie value using a React hook asuseEffect, when the page loads.