Skip to content

Commit

Permalink
Rewrite hook without luxon
Browse files Browse the repository at this point in the history
  • Loading branch information
ebma committed Dec 20, 2023
1 parent 3014e23 commit ebc5732
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { DateTime } from 'luxon';
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/compat';
import { storageService } from '../services/storage/local';
import { Storage } from '../services/storage/types';
Expand Down Expand Up @@ -43,14 +42,14 @@ export interface UseLocalStorageResponse<T> {
clear: () => void;
}

const hasExpired = (date: DateTime, expire?: number) => {
if (expire === undefined) return false;
return DateTime.now() < date.plus({ seconds: expire });
const hasExpired = (timestamp: number, expiredMillis?: number) => {
if (expiredMillis === undefined) return false;
return Date.now() < timestamp + expiredMillis;
};

const getState = <T>(key: string, defaultValue: T, parse: boolean, expire?: number): T => {
const date = expire !== undefined ? storageService.get(`${key}_`) : undefined;
if (date?.length && hasExpired(DateTime.fromMillis(Number(date)), expire)) return defaultValue;
if (date?.length && hasExpired(Date.parse(date), expire)) return defaultValue;
if (!parse) return (storageService.get(key) as T) ?? defaultValue;
const parsed = storageService.getParsed<T>(key, defaultValue) as T;
return defaultValue !== undefined
Expand All @@ -73,7 +72,7 @@ export const useLocalStorage = <T>({
const storageSet = useMemo<Storage['set']>(() => {
const internalSet = (key: string, value: unknown) => {
storageService.set(key, value);
if (expire !== undefined) storageService.set(`${key}_`, DateTime.now());
if (expire !== undefined) storageService.set(`${key}_`, Date.now());
};
return debounceTime ? debounce(internalSet, debounceTime) : internalSet;
}, [debounceTime, expire]);
Expand Down

0 comments on commit ebc5732

Please sign in to comment.