Skip to content

Bug: optimistic state (useOptimistic) shows both optimistic and returned from server data when running several async actions #28574

@acherkashin

Description

@acherkashin

I have a form with submit button. When I click on the button, I call update optimistic state and update real state as soon as action is finished. When I click on the button 3 times, I will see 6 items in the list for a while.

Issue.Demo.mp4

React version:

  • "react": "18.3.0-canary-bb0944fe5-20240313",
  • "react-dom": "18.3.0-canary-bb0944fe5-20240313"

Steps To Reproduce

  1. Click 3 times on the button

Link to repository:
https://github.com/acherkashin/react19-useOptimistic

Link to sandbox
https://stackblitz.com/~/github.com/acherkashin/react19-useOptimistic

const AddToCartForm = ({ title, addToCart, optimisticAddToCart }: AddToCartFormProps) => {
  const formAction = async (formData: FormData) => {
    const itemId = String(formData.get('itemID'));
    optimisticAddToCart({ id: itemId, title, pending: true });
    try {
      await addToCart(itemId, title);
    } catch (e) {
      console.log(e);
      // show error notification
    }
  };

  return (
    <form action={formAction}>
      <h2>{title}</h2>
      <input type="hidden" name="itemID" value={crypto.randomUUID()} />
      <button type="submit">Add to Cart</button>
    </form>
  );
};

The current behavior

I see every added item 2 times.

The expected behavior

If I add 3 elements, I should see 3 items in the list, not 6.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions