Skip to content

Commit 2f54b39

Browse files
committed
πŸ› setValue during render doesn't work, resolve #43
1 parent aff7781 commit 2f54b39

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

β€Žsrc/useLocalStorageState.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ function useClientLocalStorageState<T>(
7575
storage.set(key, newUnwrappedValue)
7676

7777
unstable_batchedUpdates(() => {
78+
// πŸ› `setValue()` during render doesn't work
79+
// https://github.com/astoilkov/use-local-storage-state/issues/43
80+
forceUpdate()
81+
7882
for (const update of activeHooks) {
7983
if (update.key === key) {
8084
update.forceUpdate()

β€Žtest.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,4 +601,23 @@ describe('createLocalStorageStateHook()', () => {
601601

602602
expect(queryByText(/^2$/u)).toBeTruthy()
603603
})
604+
605+
// https://github.com/astoilkov/use-local-storage-state/issues/43
606+
it(`setState() during render should work`, () => {
607+
function Component() {
608+
const [value, setValue] = useLocalStorageState('number', {
609+
defaultValue: 0,
610+
})
611+
612+
if (value === 0) {
613+
setValue(1)
614+
}
615+
616+
return <div>{value}</div>
617+
}
618+
619+
const { queryByText } = render(<Component />)
620+
621+
expect(queryByText(/^1$/u)).toBeTruthy()
622+
})
604623
})

0 commit comments

Comments
Β (0)