From 8f2ea48d6598da01d1ea7b5cefe4d59bae148838 Mon Sep 17 00:00:00 2001 From: Ridwan Olanrewaju Date: Sun, 23 Jul 2023 23:11:36 +0100 Subject: [PATCH] change implementation of cookie storage --- src/addons/withCookieStorage.ts | 22 +++++++--------------- src/utilities/isCookieEntry.ts | 2 +- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/src/addons/withCookieStorage.ts b/src/addons/withCookieStorage.ts index a80d1a4..5dea980 100644 --- a/src/addons/withCookieStorage.ts +++ b/src/addons/withCookieStorage.ts @@ -1,21 +1,17 @@ import { useState, useEffect, type Reducer } from "react"; import { cookieStorage } from "component"; -import { isCookieEntry, objectToStringKey } from "utilities"; +import { objectToStringKey } from "utilities"; import { getCookieValue } from "cookies"; -import type { Initial, PortalState, CookieEntry } from "definition"; +import type { PortalState, CookieEntry } from "definition"; import { usePortalImplementation } from "./withImplementation"; export function usePortalWithCookieStorage< - S extends string | CookieEntry, + S extends CookieEntry, A = undefined ->( - key: any, - initialState?: Initial, - reducer?: Reducer -): PortalState { +>(key: any, initialState: S, reducer?: Reducer): PortalState { const stringKey = objectToStringKey(key); let overrideApplicationState = false; @@ -23,7 +19,7 @@ export function usePortalWithCookieStorage< const value = getCookieValue(stringKey); if (value !== null) { overrideApplicationState = true; - return value as S; + return { ...initialState, value }; } return initialState; }); @@ -36,12 +32,8 @@ export function usePortalWithCookieStorage< }); useEffect(() => { - if (typeof state === "string") cookieStorage.setItem(stringKey, state); - else if (isCookieEntry(state)) { - const { value, ...options } = { ...state }; - const prevValue = cookieStorage.getItem(stringKey) ?? ""; - cookieStorage.setItem(stringKey, value ?? prevValue, options); - } + const { value, ...options } = state; + cookieStorage.setItem(stringKey, state.value, options); }, [state]); return [state, setState]; diff --git a/src/utilities/isCookieEntry.ts b/src/utilities/isCookieEntry.ts index 3e1b92f..71f1ff8 100644 --- a/src/utilities/isCookieEntry.ts +++ b/src/utilities/isCookieEntry.ts @@ -6,6 +6,6 @@ import { CookieEntry } from "definition"; * @param {CookieEntry} value The value to be checked. * @returns {value is CookieEntry} `true` if the entry has a `value` property, `false` otherwise. */ -export function isCookieEntry(entry: CookieEntry): entry is CookieEntry { +export function isCookieEntry(entry: S | CookieEntry): entry is CookieEntry { return entry && typeof entry === "object" && "value" in entry; }