You can use a custom local storage hook & context api for achieve this.
Here is the local storage hook:
import React from "react"
import { useState, useEffect } from "react"
type ReturnType<T> = [
T | undefined,
React.Dispatch<React.SetStateAction<T | undefined>>
]
const useLocalStorage = <T,>(key: string, initialValue?: T): ReturnType<T> => {
const [state, setState] = useState<T | undefined>(() => {
if (!initialValue) return
try {
const value = localStorage.getItem(key)
return value ? JSON.parse(value) : initialValue
} catch (error) {
return initialValue
}
})
useEffect(() => {
if (state) {
try {
localStorage.setItem(key, JSON.stringify(state))
} catch (error) {
console.log(error)
}
}
}, [state, key])
return [state, setState]
}
export { useLocalStorage }
and the context for auth:
import { useLocalStorage } from "../hooks/useLocalStorage"
export interface Auth {
username?: string
roles?: Array<string>
permissions?: Array<string>
token?: string
}
export interface AuthContextInstance {
auth?: Auth
setAuth: React.Dispatch<React.SetStateAction<Auth | undefined>>
unsetAuth: () => void
}
const AuthContext = createContext<AuthContextInstance>({
setAuth: () => {
return
},
unsetAuth: () => {
return
},
})