tRPC Optimistic Update Not Work

Live Reproduction: https://chirp-oesz5k7g2-apestein.vercel.app/ Repo: https://github.com/Apestein/chirp/tree/feature-branch More specifically: https://github.com/Apestein/chirp/blob/feature-branch/src/components/Post.tsx
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()
},
})
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()
},
})
Docs: https://create.t3.gg/en/usage/trpc#optimistic-updates I have it exactly the same so I really don't understand why this doesn't work.
0 Replies
No replies yetBe the first to reply to this messageJoin