Skip to content

Commit

Permalink
change implementation of cookie storage
Browse files Browse the repository at this point in the history
  • Loading branch information
ibnlanre committed Jul 23, 2023
1 parent f8f99ce commit 8f2ea48
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
22 changes: 7 additions & 15 deletions src/addons/withCookieStorage.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
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<S>,
reducer?: Reducer<S, A>
): PortalState<S, A> {
>(key: any, initialState: S, reducer?: Reducer<S, A>): PortalState<S, A> {
const stringKey = objectToStringKey(key);
let overrideApplicationState = false;

const [cookieState] = useState(() => {
const value = getCookieValue(stringKey);
if (value !== null) {
overrideApplicationState = true;
return value as S;
return { ...initialState, value };
}
return initialState;
});
Expand All @@ -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];
Expand Down
2 changes: 1 addition & 1 deletion src/utilities/isCookieEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<S>(entry: S | CookieEntry): entry is CookieEntry {
return entry && typeof entry === "object" && "value" in entry;
}

0 comments on commit 8f2ea48

Please sign in to comment.