Bug: useOptimistic
Opened this issue · 2 comments
React version:19.0.0
I got example from react.dev slightly modified it.
Now key
attribute derive value from data (message)
<div key={message.id}>
{message.text}
{!!message.sending && <small> (Sending...)</small>}
</div>
Steps To Reproduce
1.Open link
2.Send new message
3.Open console
The current behavior
On the image below we can see duplicating list of messages from I got example from react.dev.
There was no error in I got example from react.dev because key
gets values from index
, index
is always unique.
<div key={index}>
{message.text}
{!!message.sending && <small> (Sending...)</small>}
</div>
Code that is slightly modified by me print out following (from console):
Encountered two children with the same key,
8908d3a9-13b7-4576-bf85-e850f7ab2c1c
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version
I don't know the reason of that behaviour but I see that updateFn
in useOptimistic
is called with new message
twice:
- First time after
addOptimisticMessage
is called, - Second time while
Thread
component is re-rendered.
Hi, i tried to replicate the issue from your provided sandbox link and was unable to do so, there was no duplicating of list, there is this one typo in your code though
async function sendMessage(message) {
const sentMessage = await deliverMessage(message);
setMessages((messages) => [...messages, message]);
}
i think you intended
async function sendMessage(message) {
const sentMessage = await deliverMessage(message);
setMessages((messages) => [...messages, sentMessage ]);
}
also in actions.js you will need to set message.sending to false to recreate the example as provided
there is this one typo in your code though
yes, you are right, but for the purpose of the demonstration it doesn't matter
there was no duplicating of list
you have to debug code to see of duplication of two elements in list