Optimistic Updates - GRIM-Technologies/react-training.adv GitHub Wiki

On the page /optimistic-updates in our application, we see a list of posts. When we press "Delete" on one of these posts, the deletion takes some time to be completed. This makes the UI feel slow!

If we assume that the API call that deletes a post will succeed, we can implement an optimistic state update with the useOptimistic hook, in combination with the useTransition hook that we are now familiar with.


Task

Implement the useOptimistic hook in this example, so that the post we're trying to delete is removed immediately from the UI.

If the API call (mock function deletePost) completes (promise resolves), the list as it looks after the API call is completed, should be rendered.

If the API call fails (deletePost promise rejects), then the post that we tried to delete should be re-added.

Optional

Note that if we're not using "Server actions" or "form actions", we must label our optimistic updates as transitions.

In order to get rid of the transition around our optimistic update, we need to use form action or server actions. To make this example more realistic, implement the Delete as a form action instead.

<form action={theFormAction}>
  ...
  <button type="submit">Delete</button>
</form>

It may seem unintuitive to have a form for a simple Delete button, but for the sake of understanding the implementation requirements it will help our learning.

⚠️ **GitHub.com Fallback** ⚠️