Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 798 Bytes
76ea2b9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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];
} |