I have two components, NotificationsLabel
and NotificationsIcon
. I have a query for each component, which fetches a list of notifications:
query NotificationsLabelSearchRecommendations {
searchRecommendations {
_id
recommendationType
}
}
query NotificationsIconSearchRecommendations {
searchRecommendations {
_id
recommendationType
}
}
I also have a subscription for each component:
subscription NotificationsLabelRecommendationChanged($tenantId: String!) {
recommendationChanged(tenantId: $tenantId) {
_id
recommendationType
subscriptionPubSubType
}
}
subscription NotificationsIconRecommendationChanged($tenantId: String!) {
recommendationChanged(tenantId: $tenantId) {
_id
recommendationType
subscriptionPubSubType
}
}
Each component calls their respective query with useQuery
and calls subscribeToMore
to listen for updates. In practice, this fetches an initial list of notifications and then updates the list when a notification comes in.
However, when a subscription is retrieved by these components, I see a duplication occur. Instead of having my list of notifications increment by +1, I see the same notification twice in each component.
My question is, do I need to check for duplicates in my updateQuery
function? For example, I can do something like this:
const updateQuery = (prevData, { subscriptionData }) => {
const newRecommendation = subscriptionData?.data?.recommendationChanged;
if (!newRecommendation?._id) return prevData;
const prevRecommendations = prevData?.searchRecommendations ?? [];
const hasNewRecommendation = prevRecommendations.some(
({ _id }) => _id === newRecommendation._id
);
if (hasNewRecommendation) return prevData;
return Object.assign({}, prevData, {
searchRecommendations: [...prevRecommendations, newRecommendation],
});
}
But I’m not sure if this is required, or if there’s another way Apollo Client should be handling this.
If it is required, how do I give consideration to performance if I am adding a subscription to large list?