async atom resolves with stale value #2461
|
just trying out Jotai and ran into this issue. it appears the first resolution of a promise is able to override the resolution of a later promise: as you can see, during the second run, the result we end up with is displaying the wrong content for id 9005 - it's actually the content from the post with id 9001, the one that displays initially. here's the sandbox: https://codesandbox.io/p/sandbox/cool-shape-4j92jf?file=%2FApp.tsx&utm_medium=sandpack it's based on your example here: https://tutorial.jotai.org/examples/hackerNews the only difference is I introduced a delay to see how reliable it was: function delay() {
return new Promise(resolve => {
setTimeout(resolve, Math.random()*2000 + 500);
});
}
const postId = atom(9001)
const postData = atom(async (get) => {
const id = get(postId)
const response = await fetch(
`https://hacker-news.firebaseio.com/v0/item/${id}.json`
)
await delay(); // 👈
const data: PostData = await response.json()
return data
})this essentially just simulates a delay, which could happen on a slow network. interestingly, if I add e.g. the issue is only triggered if you reload the page and then quickly hit the arrow button a few times. so it would appear only the first promise can end up beating later promises in a race - after the first promise resolves, once the promise stream is going, so to speak, there is no problem. am I explaining this well? 😅 |
Replies: 2 comments 9 replies
Yeah, it's one of the hardest challenges to implement Jotai.
No, I'm not sure if I understand your problem. Oh, 9005 after the reload. Interesting. Why can it be not 9001 after the reload??? |
|
@mindplay-dk Hi, I just realized that it's probably because the older version of Jotai. https://stackblitz.com/edit/vitejs-vite-56vtp9?file=src%2FApp.tsx&terminal=dev |

@mindplay-dk Hi, I just realized that it's probably because the older version of Jotai.
Can you try with the latest version please?
https://stackblitz.com/edit/vitejs-vite-56vtp9?file=src%2FApp.tsx&terminal=dev