Optimistic updates not working?

Does anyone have a working code snippet using the latest create t3?
2 Replies
dan
dan15mo ago
Include the code here and someone will might be able to see whats wrong. There are examples on the react query docs on setting up optimistic updates, you can do the same with trpc. https://tanstack.com/query/latest/docs/react/guides/optimistic-updates
Optimistic Updates | TanStack Query Docs
When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could ...
Zion
Zion15mo ago
const { mutate, isLoading } = api.todo.create.useMutation({
async onMutate(newTodo) {
resetField("title");
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todo.userList.cancel();

// Get the data from the queryCache
const prevData = utils.todo.userList.getData();

const optimisticTodo = {
title: newTodo.title,
userId: session.data?.user?.id ?? "",
createdAt: new Date(),
done: false,
} as Todo;

// Optimistically update the data with our new post
utils.todo.userList.setData(undefined, (old) => [
optimisticTodo,
...(old ?? []),
]); // Use updater function

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newTodo, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todo.userList.setData(undefined, (old) => ctx?.prevData ?? old);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todo.userList.invalidate();
},
});
const { mutate, isLoading } = api.todo.create.useMutation({
async onMutate(newTodo) {
resetField("title");
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todo.userList.cancel();

// Get the data from the queryCache
const prevData = utils.todo.userList.getData();

const optimisticTodo = {
title: newTodo.title,
userId: session.data?.user?.id ?? "",
createdAt: new Date(),
done: false,
} as Todo;

// Optimistically update the data with our new post
utils.todo.userList.setData(undefined, (old) => [
optimisticTodo,
...(old ?? []),
]); // Use updater function

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newTodo, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todo.userList.setData(undefined, (old) => ctx?.prevData ?? old);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todo.userList.invalidate();
},
});
exmaple for a todo app
Want results from more Discord servers?
Add your server