Skip to content

[BUG] addReaction.onQueryStarted should also update getPost(id) query cache. #47

@nandin-borjigin

Description

@nandin-borjigin

In the RTK version of the tutorial, addReaction mutation optimistically updates the reaction data in the getPosts cache. But it should also update the cache for getPost(id) query as well. Otherwise, addReaction mutation is not reflected in the SinglePostPage.

I cannot contribute a PR because this version of code doesn't have a corresponding branch (it only has a tag).

async onQueryStarted({ postId, reaction }, { dispatch, queryFulfilled }) {
// `updateQueryData` requires the endpoint name and cache key arguments,
// so it knows which piece of cache state to update
const patchResult = dispatch(
apiSlice.util.updateQueryData('getPosts', undefined, (draft) => {
// The `draft` is Immer-wrapped and can be "mutated" like in createSlice
const post = draft.find((post) => post.id === postId)
if (post) {
post.reactions[reaction]++
}
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
},

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions