Skip to content

Commit

Permalink
prevent hydration error
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikmonsen committed Nov 5, 2024
1 parent f68ca6a commit fda4d80
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import {Link, Navbar, NavbarBrand, NavbarContent, NavbarItem} from '@nextui-org/react';
import React from 'react';
import React, {useEffect, useState} from 'react';
import {usePathname, useRouter} from 'next/navigation';
import SearchBar from '@/components/SearchBar';
import Image from 'next/image';
Expand All @@ -12,10 +12,17 @@ import {UserDetails} from '@/components/UserDetails';
export default function Header() {
const { authenticated , user } = useAuth();
const router = useRouter();
const [ isMounted, setIsMounted ] = useState(false);

const pathname = usePathname() || '';
const titlepageRegex = /^\/\d+$/;

// To prevent hydration error when displaying the user details as these are rendered from session storage
useEffect(() => {
setIsMounted(true);
return () => setIsMounted(false);
}, []);

return (
<Navbar maxWidth='xl'>
<NavbarBrand>
Expand All @@ -36,7 +43,7 @@ export default function Header() {
</NavbarContent> }
<NavbarContent justify="end">
<NavbarItem className="lg:flex">
{ authenticated ? (
{ authenticated && isMounted ? (
<>
<UserDetails name={user?.name ?? ''} className="px-2.5"/>
<LogoutButton/>
Expand Down
7 changes: 5 additions & 2 deletions src/hooks/usePersistState.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import {useEffect, useMemo, useState} from 'react';

// Check if window is defined (i.e. if we are in the browser)
const storage = typeof window !== 'undefined' ? sessionStorage : null;

// Hook to persist state in session storage
export default function usePersistState<T>(id: string, initialValue: T): [T, (newState: T) => void] {

const value = useMemo(() => {
const sessionStorageValue = sessionStorage.getItem('state:' + id);
const sessionStorageValue = storage?.getItem('state:' + id);

if (sessionStorageValue) {
return JSON.parse(sessionStorageValue) as T;
Expand All @@ -18,7 +21,7 @@ export default function usePersistState<T>(id: string, initialValue: T): [T, (ne

useEffect(() => {
const stateStr = JSON.stringify(state);
sessionStorage.setItem('state:' + id, stateStr);
storage?.setItem('state:' + id, stateStr);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);

Expand Down

0 comments on commit fda4d80

Please sign in to comment.