I'm been using useContext to get my variables from one page to the other and I implemented localStorage so I refresh the page. However, when I refresh my portals
page I'm getting this error:
JSON Parse error: Unexpected identifier "undefined"
The weird part is that, if I refresh it's child page editPortal
, I get no error!
Can someone help me please?
_app.tsx :
import { PortalContext } from '../context/PortalContext';
function MyApp({ Component, pageProps }) {
const [portal, setPortal] = useState<Portal>();
const [loading, setLoading] = useState(true);
useEffect(() => {
const portal = localStorage.getItem('portal');
if (portal) {
setPortal(JSON.parse(portal));
}
setLoading(false);
}, []);
function choosePortal(portal: Portal) {
setPortal(portal);
if (typeof window !== 'undefined') {
localStorage.setItem('portal', JSON.stringify(portal));
}
}
return (
<PortalContext.Provider value={{ portal, escolhePortal, loading }}>
<main>
<Header />
<Component {...pageProps} />
</main>
</PortalContext.Provider>
);
}
portals.tsx
export default function Portals() {
const router = useRouter();
const { choosePortal } = useContext(PortalContext);
const baseName = Array.isArray(router.query.baseName)
? router.query.nomeBase[0]
: router.query.nomeBase;
const portal: Portal = GetPortals(baseName);
choosePortal(portal);
if (portal) {
return <h1>portal.title</h1>
}
Thanks a lot!