I have a project with nextJs and typescript. I used context API for handling global states in my application. My problem is when I navigate between pages my state revaluates again.(i used nextjs Link tag) in other words, I want my context updated only once and not each time I navigate between pages. this is my context
import React, {createContext, useState} from "react";
export type ResourcesType =
'ALL'
| 'ORDERS'
| 'ORDERS_CANCELLATION'
| 'ORDERS_PARTIAL_PAID';
export type AccessType = 'ACT' | 'READ' | 'UPDATE' | 'CREATE' | 'DELETE' | 'All';
export type AccessLevel = 'DO' | 'REQUEST' | 'APPROVE';
export type PermissionType = {
[key1 in ResourcesType]: {
[key2 in AccessType]: AccessLevel
}
} | null;
const PermissionsContext = createContext<{
permissions: PermissionType,
setPermissionsHandler: (permissions: PermissionType) => void
}>({
permissions: null,
setPermissionsHandler: (permissions: PermissionType) => {}
});
export function PermissionsProvider(props: any) {
const [permissions, setPermissions] = useState<PermissionType>(null);
const setPermissionsHandler = (permissions: PermissionType) => {
setPermissions(permissions);
}
const context = {
permissions,
setPermissionsHandler
}
return <PermissionsContext.Provider value={context}>
{props.children}
</PermissionsContext.Provider>
}
export default PermissionsContext;
and I call setPermissionsHandler in my header component and my header component is in all pages.
this is my header component
const Header = () => {
const permissionsCtx = useContext(PermissionsContext);
const initialCtx = useContext(InitialContext);
useEffect(() => {
console.log(permissionsCtx.permissions,'INN');
if (!permissionsCtx.permissions) {
console.log('OH')
const initialInstance = new HandleInitialize();
initialInstance.getInitialData()
.then(res => {
permissionsCtx.setPermissionsHandler(res.data.result.permissions);
})
.catch(e => console.log(e));
}
}, []);
return (
<div>
Hi
</div>
);
};
import type {AppProps} from "next/app";
import useRouterStatus from "../hooks/useRouterStatus";
import PrimeReact from "primereact/api";
import "nprogress/nprogress.css";
/*import "primereact/resources/themes/lara-light-indigo/theme.css";*/
import "../styles/override-theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import "tailwindcss/tailwind.css";
import "../styles/typography.css";
import "../styles/globals.css";
import "../styles/primefaces-overrides.css";
import {PermissionsProvider} from "../store/persmissions";
import {InitialProvider} from "../store/initial";
import {useEffect} from "react";
import {HandleInitialize} from "../adapter/HandleInitialize";
function MyApp({Component, pageProps}: AppProps) {
return <PermissionsProvider>
<Component {...pageProps} />
</PermissionsProvider>;
}
export default MyApp;