useOptimistic hook reverts to old value even after server action succeds
Unanswered
Philippine Crocodile posted this in #help-forum
Philippine CrocodileOP
Hi guys, I am having an issue with the useOptimistic hook, I am trying to update the status value in an object. The server action is successfully updateing the value but the useOptimistic hook initially shows the optimistic update but reverts to the previous value. Here is the server action
"use server";
import { db } from "@/lib/db";
import { updateTaskStatusSchema } from "@/schema";
import { auth } from "@clerk/nextjs/server";
import { revalidatePath } from "next/cache";
export async function updateTaskAction(formData:FormData) {
const {orgId, userId} = auth()
// if there is no orgId or no userId return early
if(!orgId || !userId) {
throw new Error('You must be logged in to update a task')
}
const validatedFields = updateTaskStatusSchema.safeParse({
id: formData.get('id'),
status: formData.get('status'),
projectId: formData.get('projectId')
})
if(!validatedFields.success) {
throw new Error('Invalid fields')
}
const updatedStatus = await db.task.update({
where: {
projectId: validatedFields.data.projectId,
id: validatedFields.data.id
},
data: {
status: validatedFields.data.status
}
})
revalidatePath(`/organization/${orgId}/projects/${validatedFields.data.projectId}?taskId=${updatedStatus.id}`)
return updatedStatus;
} and here is the implementation I have for the hook const [pending, startTransition] = useTransition();
const [optimisticTask, setOptimisticTask] = useOptimistic(
task,
(state, newTask: Task) => {
return {
...state,
status: newTask.status,
};
},
);1 Reply
Philippine CrocodileOP
Here is the form -
<form
action={async (formData: FormData) => {
const status = formData.get("status") as Status;
startTransition(async () => {
setOptimisticTask({
id: optimisticTask.id,
projectId: optimisticTask.projectId,
status: status,
title: optimisticTask.title,
cost: optimisticTask.cost,
startDate: optimisticTask.startDate,
dueDate: optimisticTask.dueDate,
orgId: optimisticTask.orgId,
userId: optimisticTask.userId,
});
await updateTaskAction(formData);
setSelectedTask(optimisticTask);
router.push(
`/organization/${task.orgId}/projects/${task.projectId}?taskId=${task.id}`,
);
});
}}
>
<Input type="hidden" name="id" value={task.id} />
<Input type="hidden" name="projectId" value={task.projectId} />
<Input type="hidden" name="status" value="inProgress" />
<Button size="sm" variant="ghost" type="submit">
In Progress
</Button>
</form>