Next.js Discord

Discord Forum

problems in using useOptimistic()

Unanswered
tabahi posted this in #help-forum
Open in Discord
app/page.tsx
"use client";
import { createTodo } from "@/actions/createTodo";
import { useOptimistic } from "react";
type Todo = {
  todoTask: string;
  ticked: boolean;
};
export default function Home() {
  const todos: Todo[] = [
    { todoTask: "something1", ticked: true },
    { todoTask: "something2", ticked: true },
    { todoTask: "something3", ticked: false },
  ];
  const [optimisticTodos, addOptimisticTodo] = useOptimistic<Todo[], Todo>(
    todos,
    (state, newTodo) => [...state, newTodo]
  );
  return (
    <main>
      <h1>Home</h1>
      <h2>Welcome to the To Do List.</h2>
      <div>
        <h3>Tasks</h3>
        <ul>
          {optimisticTodos.map((todo, index) => (
            <li key={index}>
              <input type="checkbox" defaultChecked={todo.ticked} />
              {todo.todoTask}
            </li>
          ))}
        </ul>
        <form
          action={async (formData: FormData) => {
            const todoInput = formData.get("todoInput") as string;
            addOptimisticTodo({ todoTask: todoInput, ticked: false });
            await createTodo(formData);
          }}
        >
          <input type="text" name="todoInput" placeholder="Add a new task" />
          <button type="submit">Add</button>
        </form>
      </div>
    </main>
  );
}

i was testing with useOptimistic
I've attached a video of the current behaviour, basically the todoTask appears for a second and disappears, also createTodo function in the above code, just contains a console.log, for now

8 Replies

bump!
does your server action revalidate page again? as optimistic shows its "cached" data and resets to what was provided when the action finished edit: i see you have them hardcoded and you should folow below's message for making db
Yacare Caiman
The change you make in useOptimistic will only be displayed while the mutation (createTodo in this case) is running. Afterwards, it's expected that your function will receive updated ToDos from the server.

So you will need to move the hard-coded ToDos to an actual database and revalidate the request to fetch those ToDos from within the createToDo server action.
Spectacled bear
Or can't he just update the state ?


            const [todos, setTodos] = useState([
    { todoTask: "something1", ticked: true },
    { todoTask: "something2", ticked: true },
    { todoTask: "something3", ticked: false },
  ]);


            // In your form action
            const todoInput = formData.get("todoInput") as string;
            addOptimisticTodo({ todoTask: todoInput, ticked: false });
            const todo = await createTodo(formData);
            if (todo) setTodos((prev) => [...prev, todo])
          }}
the optimistic isnt really needed, and they should just use useState then
Spectacled bear
Yes it is, because optimistic is used to optimistically update the state before getting the the backend response, and then, you save changes if succeed or you rollback if it failed
For me, optimistic is like 'I consider that my backend did what he has to do, I will save the changes when I get the response or revert them if it failed'
Like react-query with a create mutation, you optimistically add your value, then when you get the backend response, depending on if it was an error or not, you revert or save the changes