Spaces:
Sleeping
Sleeping
import { useEffect, useState } from "react"; | |
import axios from "@/utils/axios"; | |
export const usePersistentState = (key: string, defaultValue: any) => { | |
const [state, setState] = useState(() => { | |
if (typeof window !== 'undefined') { | |
const persistedState = localStorage?.getItem(key); | |
if (persistedState) { | |
axios.defaults.headers = {...JSON.parse(persistedState), Authorization: `Bearer ${JSON.parse(persistedState).Authorization}`} | |
} | |
return persistedState !== null ? JSON.parse(persistedState) : defaultValue; | |
} | |
return defaultValue; | |
}); | |
useEffect(() => { | |
localStorage.setItem(key, JSON.stringify(state)); | |
axios.defaults.headers = {...state, Authorization: `Bearer ${state.Authorization}`} | |
}, [key, state]); | |
return [state, setState]; | |
} |