I want a component to render based on token is available or not - similar to the jwt localstorage authentication. The issue i found that whenever I refresh the page when the token is available still the component in condition is also flashes or rendered, after that the token condition works and desired component is rendered. My backend is running on another port which is using nodejs express Here is the code.
export default function Home() {
const [user, setUser] = useState(null);
const [token, setToken] = useState(null);
useEffect(() => {
setToken(localStorage.getItem("token"));
}, []);
useEffect(() => {
if (token) {
getuser(token);
}
}, [token]);
const getuser = async (token) => {
const res = await axios.get("http://localhost:5000/result", {
headers: {
Authorization: `Bearer ${token}`,
},
});
setUser(res.data);
}
return (
<>
{token ? (
<>
<Navbar user={user} />
<FloatingButton />
</>
) : (
<>
<HomePage />
</>
)}
</>
);
}
I am new in Nextjs and moved from reactjs so i tried ssr in nextjs using getserversideprops but still the issue was not resolved as i found that localstorage can't be accessed through ssr..(i don't know if it is correct or not)