Lautaro_dapin
Lautaro_dapin14mo ago

Optimistic update on infinite query

Node 18.12.1 with pnpm trpc v 10.28.1 I have the following query to render a list of posts
// List of posts
export default function ListPage(){
const router = useRouter()
const q = router.query.q as string || ''
const {data} = api.post.feed.useInfiniteQuery({q}, {
getNextPageParam: lastPage => lastPage.nextCursor,
})
const posts = data?.pages.flatMap(page => page.items)

return (
<>
{posts.map(post => <Post post={post}/> )}
</>
)
}
// List of posts
export default function ListPage(){
const router = useRouter()
const q = router.query.q as string || ''
const {data} = api.post.feed.useInfiniteQuery({q}, {
getNextPageParam: lastPage => lastPage.nextCursor,
})
const posts = data?.pages.flatMap(page => page.items)

return (
<>
{posts.map(post => <Post post={post}/> )}
</>
)
}
Then inside the Post component i have the following muutation to toggle a like server state But for some reason when i want to update the cache for an optimistic update the cache is always empty, idk why
const utils = api.useContext()
const toggleLikeMutation = api.post.toggleLikePost.useMutation({
onMutate: async () => {
const snapshot = utils.post.feed.getInfiniteData({q: ''})
console.log({snapshot}) // <---- EMPTY
if (!snapshot) return {snapshot}
utils.post.feed.setInfiniteData({}, () => {
return {
...snapshot,
pages: snapshot.pages.map(page => {
return {
...page,
items: page.items.map(post => {
if (post.id !== id) return post
return {
...post,
liked: !post.liked
}
})
}
})
}
})
return {
snapshot
}
},

onError: (error, {postId}, ctx) => {
ctx?.snapshot && utils.post.feed.setInfiniteData({}, () => ctx.snapshot)
},

async onSuccess() {
await utils.post.feed.invalidate()

}
})
const utils = api.useContext()
const toggleLikeMutation = api.post.toggleLikePost.useMutation({
onMutate: async () => {
const snapshot = utils.post.feed.getInfiniteData({q: ''})
console.log({snapshot}) // <---- EMPTY
if (!snapshot) return {snapshot}
utils.post.feed.setInfiniteData({}, () => {
return {
...snapshot,
pages: snapshot.pages.map(page => {
return {
...page,
items: page.items.map(post => {
if (post.id !== id) return post
return {
...post,
liked: !post.liked
}
})
}
})
}
})
return {
snapshot
}
},

onError: (error, {postId}, ctx) => {
ctx?.snapshot && utils.post.feed.setInfiniteData({}, () => ctx.snapshot)
},

async onSuccess() {
await utils.post.feed.invalidate()

}
})
0 Replies
No replies yetBe the first to reply to this messageJoin