Conditional rendering based on state with app folder
Unanswered
Odorous house ant posted this in #help-forum
Odorous house antOP
How am I supposed to solve the hydration error?
Warning: Expected server HTML to contain a matching <div> in <div>.
at div"use client"
import {useAuth} from "bidding-db-client";
import Image from "next/image";
export default function SignIn() {
const auth = useAuth()
const user = auth.user()
if (user === null) {
return <button className={'btn btn-primary'}>Login</button>
}
return <div className="dropdown dropdown-end">
<label tabIndex={0} className="btn btn-ghost btn-circle avatar">
<div className="w-10 rounded-full">
<Image src={"/profile.webp"} alt={'Menu'} width={100} height={100}/>
</div>
</label>
</div>
}20 Replies
Gull Dong
@Odorous house ant shouldn't the html be wrapped with ( )
Odorous house antOP
does not matter I think
Gull Dong
you could try it just in case but as usual i dont know that much about syntax errors
Odorous house antOP
I already tried it now, same issue
it's more likely the useAuth that doesn't work server side causing issues
nope
Odorous house antOP
but I dont know what to do
one second
Gull Dong
lol it works for me
you're getting an error because user is initially empty and the server expects it to be empty
you gotta listen to when the component mounts before rendering
you could create a hook
import { useEffect, useState } from "react";
export const useMounted = () => {
const [mounted, setMounted] = useState<boolean>(false);
useEffect(() => {
setMounted(true);
return () => {
setMounted(false);
};
}, []);
return mounted;
};and use it in your page
try this
"use client"
import {useMounted} from "@_lib/hooks/useMounted"
import {useAuth} from "bidding-db-client";
import Image from "next/image";
export default function SignIn() {
const auth = useAuth()
const isMounted = useMounted();
const user = auth.user()
if(isMounted){
if (user === null) {
return <button className={'btn btn-primary'}>Login</button>
}
return <div className="dropdown dropdown-end">
<label tabIndex={0} className="btn btn-ghost btn-circle avatar">
<div className="w-10 rounded-full">
<Image src={"/profile.webp"} alt={'Menu'} width={100} height={100}/>
</div>
</label>
</div>
}
}Odorous house antOP
hmmm ok
is there a topic on this somewhere?
@Odorous house ant do you still get the error?