From 60bda6304504e7ab0c5a2c69b4a178c26f9c7e81 Mon Sep 17 00:00:00 2001 From: David Totraev Date: Sat, 23 Nov 2024 17:04:00 +0500 Subject: [PATCH] fix: ssr issues in usePersistState --- src/hooks/usePersistState.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/hooks/usePersistState.ts b/src/hooks/usePersistState.ts index bcab1a2..ed007de 100644 --- a/src/hooks/usePersistState.ts +++ b/src/hooks/usePersistState.ts @@ -2,9 +2,14 @@ import { type SetStateAction, type Dispatch, useState, useEffect } from "react"; -export function usePersistState(key: string, storage: Storage, initialState?: S): [S, Dispatch>] { +export function usePersistState(key: string, storage: Storage, initialState: S): [S, Dispatch>] { function getDefaultState() { const defaultValue = typeof initialState === "function" ? (initialState as () => S)() : initialState; + + if (typeof storage === "undefined") { + return defaultValue; + } + const persistValue = storage.getItem(key); const defaultState = persistValue ? (JSON.parse(persistValue) as S) : null;