setInfiniteQueryData and getInfiniteQueryData compatibility

I want to setInfiniteQueryData to old data (before mutation). I have a following code:
const postMessage = trpc.useMutation("guestBook.postMessage", {
onMutate: async (newMessage) => {
ctx.cancelQuery(["guestBook.getPaginated"]);

const previousDataGetPaginated = ctx.getInfiniteQueryData(["guestBook.getPaginated", { limit: 5 }]);

if (previousDataGetPaginated) {
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5 }], (oldData) => {
if (!oldData) {
return {
pages: [],
pageParams: [],
}
}

if (oldData.pages[0]) {
oldData.pages[0].items.unshift({ ...newMessage, id: "0" })
}

return oldData;
})
}

return { previousDataGetPaginated };
},
onError: (err, newMessage, context) => {
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5}], context?.previousDataGetPaginated);
},
onSettled: () => {
ctx.invalidateQueries(['guestBook.getPaginated']);
},
});
const postMessage = trpc.useMutation("guestBook.postMessage", {
onMutate: async (newMessage) => {
ctx.cancelQuery(["guestBook.getPaginated"]);

const previousDataGetPaginated = ctx.getInfiniteQueryData(["guestBook.getPaginated", { limit: 5 }]);

if (previousDataGetPaginated) {
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5 }], (oldData) => {
if (!oldData) {
return {
pages: [],
pageParams: [],
}
}

if (oldData.pages[0]) {
oldData.pages[0].items.unshift({ ...newMessage, id: "0" })
}

return oldData;
})
}

return { previousDataGetPaginated };
},
onError: (err, newMessage, context) => {
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5}], context?.previousDataGetPaginated);
},
onSettled: () => {
ctx.invalidateQueries(['guestBook.getPaginated']);
},
});
But line:
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5}], context?.previousDataGetPaginated);
ctx.setInfiniteQueryData(["guestBook.getPaginated", { limit: 5}], context?.previousDataGetPaginated);
is having error in vscode:
Argument of type 'InfiniteData<{ items: { message: string; name: string; id: string; }[]; nextCursor: string | undefined; }> | undefined' is not assignable to parameter of type 'Updater<InfiniteData<{ items: { message: string; name: string; id: string; }[]; nextCursor: string | undefined; }> | undefined, InfiniteData<{ items: { message: string; name: string; id: string; }[]; nextCursor: string | undefined; }>>'. Type 'undefined' is not assignable to type 'Updater<InfiniteData<{ items: { message: string; name: string; id: string; }[]; nextCursor: string | undefined; }> | undefined, InfiniteData<{ items: { message: string; name: string; id: string; }[]; nextCursor: string | undefined; }>>'.ts(2345)
1 Reply
karlosos
karlososOP3y ago
This would work for setQueryData and getQueryData
Want results from more Discord servers?
Add your server