2022-07-17 00:51:21 +00:00
|
|
|
import React, { useCallback, useState } from "react";
|
2022-06-11 03:08:49 +00:00
|
|
|
import { localStorageSaveJSON, useLocalStorageJSONLoad, useLocalStorageJSONState } from "../generic/storage/json";
|
|
|
|
import { AuthContextContents } from "./base";
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Hook which combines {@link useState}, {@link useLocalStorageJSONLoad}, and {@link localStorageSaveJSON}.
|
|
|
|
*/
|
2022-07-17 00:51:21 +00:00
|
|
|
export function useLocalStorageAuthState(key: string): [AuthContextContents | null, React.Dispatch<AuthContextContents | null>] {
|
|
|
|
const [state, setStateInner] = useState<AuthContextContents | null>(null);
|
2022-06-11 03:08:49 +00:00
|
|
|
|
|
|
|
const validateAndSetState = useCallback(
|
|
|
|
(data: any) => {
|
|
|
|
// Convert expiresAt to a Date, since it is stringified on serialization
|
|
|
|
data = { ...data, expiresAt: new Date(data.expiresAt) }
|
|
|
|
|
|
|
|
// Refuse to load expired data
|
|
|
|
if (new Date().getTime() >= data.expiresAt.getTime()) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
setStateInner(data)
|
|
|
|
},
|
|
|
|
[setStateInner]
|
|
|
|
)
|
|
|
|
|
|
|
|
useLocalStorageJSONLoad(key, validateAndSetState);
|
|
|
|
|
|
|
|
const setState = useCallback(
|
|
|
|
(value: AuthContextContents) => {
|
|
|
|
localStorageSaveJSON(key, value);
|
2022-07-17 00:51:21 +00:00
|
|
|
validateAndSetState(value);
|
2022-06-11 03:08:49 +00:00
|
|
|
},
|
|
|
|
[key, validateAndSetState]
|
|
|
|
);
|
|
|
|
|
|
|
|
return [state, setState];
|
|
|
|
}
|