const { mutate, isLoading } = api.main.updateLikes.useMutation({
async onMutate(newPost) {
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await ctx.main.getAll.cancel()
// Get the data from the queryCache
const prevData = ctx.main.getAll.getData()
// Optimistically update the data with our new post
ctx.main.getAll.setData({ limit: 25 }, (old) => {
console.log(prevData) //Problem HERE, both prevData and old is undefined
if (!old) throw "no old data"
const updatedPosts = old.posts.map((post) =>
post.id === newPost.postId ? { ...post, likedBy: [] } : post
)
const newObj = { ...old, posts: updatedPosts }
return newObj
})
// Return the previous data so we can revert if something goes wrong
return { prevData }
},
onError: (e, newPost, prevContext) => {
ctx.main.getAll.setData({ limit: 25 }, prevContext?.prevData)
const otherErrorMessage = e.message
if (otherErrorMessage) toast.error(otherErrorMessage)
else toast.error("unknown error")
},
onSettled() {
// Sync with server once mutation has settled
void ctx.main.getAll.invalidate()
},
})