T
TanStack3y ago
correct-apricot

Cache contains duplicate data somehow

I have a useQuery like this:
function fetchMessages(dmID: number): Promise<Message[]> {
const data = await fetchWrapper(`/messages?dm_id=${dmID}`)
return data.messages
}

function useGetMessages(dmID: number) {
return useQuery(["messages", dmID], () => fetchMessages(dmID), {
enabled: dmID !== undefined
});
}
function fetchMessages(dmID: number): Promise<Message[]> {
const data = await fetchWrapper(`/messages?dm_id=${dmID}`)
return data.messages
}

function useGetMessages(dmID: number) {
return useQuery(["messages", dmID], () => fetchMessages(dmID), {
enabled: dmID !== undefined
});
}
Which fetches a list for messages for the given dmID. The response will look like this:
[{
"content": "one",
"dm_id": 3,
"id": "1"
}, {
"content": "two",
"dm_id": 3,
"id": "2"
}, {
"content": "three",
"dm_id": 3,
"id": "3"

}]
[{
"content": "one",
"dm_id": 3,
"id": "1"
}, {
"content": "two",
"dm_id": 3,
"id": "2"
}, {
"content": "three",
"dm_id": 3,
"id": "3"

}]
In the UI, I am editing the message with the id 2. That will send a websocket event to the server. That server will broadcast the event to all clients with this payload:
{
type: "Edit"
payload: {
id: "2",
content: "{...}"
}
}
{
type: "Edit"
payload: {
id: "2",
content: "{...}"
}
}
I capture this event and trying to invalidate the query using setQueryData like this:
queryClient.setQueryData(data => {
//....
})
queryClient.setQueryData(data => {
//....
})
The problem is that data contains duplicate ids. Like this:
[{
"content": "one",
"dm_id": 3,
"id": "2"
}, {
"content": "two",
"dm_id": 3,
"id": "2"
}, {
"content": "three",
"dm_id": 3,
"id": "3"

}]
[{
"content": "one",
"dm_id": 3,
"id": "2"
}, {
"content": "two",
"dm_id": 3,
"id": "2"
}, {
"content": "three",
"dm_id": 3,
"id": "3"

}]
Don't know how. The first element id value should be 1 in cache right?
2 Replies
like-gold
like-gold3y ago
must be an error somewhere in your setQueryData call
correct-apricot
correct-apricotOP3y ago
I am using setQueryData in only one place. Also I am using next.js.

Did you find this page helpful?