Skip to content

Commit

Permalink
keep originally set complex objects
Browse files Browse the repository at this point in the history
  • Loading branch information
sskirby committed Jan 11, 2023
1 parent bbdeaad commit 3b72152
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/useSessionStorage/useSessionStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,18 @@ describe('useSessionStorage()', () => {
expect(renderCount).toBe(2)
})

test('for complex values, what you set is exactly what you get', () => {
const { result } = renderHook(() => useSessionStorage('count', {}))

const newValueA = { a: 1 }
act(() => {
const setState = result.current[1]
setState(newValueA)
})

expect(result.current[0]).toBe(newValueA)
})

test('setValue is referentially stable', () => {
const { result } = renderHook(() => useSessionStorage('count', 1))

Expand Down
8 changes: 6 additions & 2 deletions src/useSessionStorage/useSessionStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ function useSessionStorage<T>(
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState<T>(readValue)
// create a new empty object to keep track of the identity of the hook
const [source] = useState({})

// Return a wrapped version of useState's setter function that ...
// ... persists the new value to sessionStorage.
Expand All @@ -65,7 +67,7 @@ function useSessionStorage<T>(

// We dispatch a custom event so every useSessionStorage hook are notified
const customEvent = new CustomEvent('session-storage', {
detail: { key },
detail: { key, source },
})
window.dispatchEvent(customEvent)
} catch (error) {
Expand All @@ -91,9 +93,11 @@ function useSessionStorage<T>(
const handleStorageChangeOnSamePage = useCallback(
(event: CustomEvent) => {
if (event.detail.key !== key) return
// don't reset the value of the hook that emitted the event
if (event.detail.source === source) return
setStoredValue(readValue())
},
[key, readValue],
[key, readValue, source],
)
// this is a custom event, triggered in writeValueTosessionStorage
// See: useSessionStorage()
Expand Down

0 comments on commit 3b72152

Please sign in to comment.