Skip to content

Commit

Permalink
fix(hooks): add golbal update to effect hook
Browse files Browse the repository at this point in the history
  • Loading branch information
xiejay97 committed May 8, 2023
1 parent 4d0422b commit 457dbe4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
10 changes: 7 additions & 3 deletions packages/hooks/src/createGlobalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ImmerHook, Updater } from './useImmer';
import { freeze, produce } from 'immer';
import { useState } from 'react';

import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';
import { useUnmount } from './useUnmount';

interface GlobalStateHook<S> {
Expand Down Expand Up @@ -34,9 +35,12 @@ export function createGlobalState<S>(initialValue?: S): GlobalStateHook<S | unde
() => {
const [state, setState] = useState(store.state);

if (!store.updates.has(setState)) {
store.updates.add(setState);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
useIsomorphicLayoutEffect(() => {
if (!store.updates.has(setState)) {
store.updates.add(setState);
}
});

useUnmount(() => {
store.updates.delete(setState);
Expand Down
16 changes: 10 additions & 6 deletions packages/hooks/src/storage/useStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { AbstractStorage } from './storage';
import { isNull, isUndefined } from 'lodash';
import { useEffect, useMemo, useState } from 'react';

import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect';
import { LocalStorageService } from './localStorage';
import { STRING_PARSER } from './parser';

Expand Down Expand Up @@ -64,12 +65,15 @@ export function useStorage<V, K = string>(
}, [SERVICE, defaultValue, deserializer, key, serializer]);
const [, setOriginValue] = useState(SERVICE.getItem(key));

const updatesOfKey = updates.get(key);
if (isUndefined(updatesOfKey)) {
updates.set(key, new Set([setOriginValue]));
} else if (!updatesOfKey.has(setOriginValue)) {
updatesOfKey.add(setOriginValue);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
useIsomorphicLayoutEffect(() => {
const updatesOfKey = updates.get(key);
if (isUndefined(updatesOfKey)) {
updates.set(key, new Set([setOriginValue]));
} else if (!updatesOfKey.has(setOriginValue)) {
updatesOfKey.add(setOriginValue);
}
});

useEffect(() => {
updates.get(key)?.delete(setOriginValue);
Expand Down

0 comments on commit 457dbe4

Please sign in to comment.