hub-api-playground / utils /usePersistentState.ts
Esteves Enzo
persistant store for authorization
76ea2b9
raw history blame
No virus
798 Bytes
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];
}