atomWithRefresh doest not work with store.set #2909
Answered
by
dai-shi
rikisamurai
asked this question in
Q&A
-
Currently, using atomWithRefresh in hooks is consistent with the documentation
But using reproduction it('should create refreshable atom with sync value in store', () => {
const mockFetch = vi.fn()
const store = createStore()
let count = 0
const countAtom = atomWithRefresh(() => {
mockFetch()
return ++count
})
expect(mockFetch).toHaveBeenCalledTimes(0)
expect(store.get(countAtom)).toBe(1) // trigger init
expect(mockFetch).toHaveBeenCalledTimes(1)
expect(store.get(countAtom)).toBe(1) // Same value without refresh, only init once
expect(mockFetch).toHaveBeenCalledTimes(1)
store.set(countAtom) // Refresh, but not trigger init
expect(mockFetch).toHaveBeenCalledTimes(1)
expect(store.get(countAtom)).toBe(2) // trigger init again
expect(mockFetch).toHaveBeenCalledTimes(2)
expect(count).toBe(2)
}) |
Beta Was this translation helpful? Give feedback.
Answered by
dai-shi
Jan 6, 2025
Replies: 1 comment
-
Atoms are lazily evaluated by default. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
rikisamurai
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Atoms are lazily evaluated by default.
Try adding
store.sub(countAtom, () => {})
to explicitly mount it. Mounted atoms are evaluated eagerly.