Hi,
I am having an issue in rerendering a list cell after creating an item, to add the item to the list. Normally it is enough to import the QUERY
to the NewItem file and adding it with variables to refetchQueries
+ awaitRefetchQueries
. But this time I have four different list cells, who all have different parameters.
The query looks roughly like this:
export const QUERY = gql`
query FindItems($id: String!,$search: String) {
items(id: $id, search: $search) {
id
}
props(id: $id) { // not sure if this second query is important for this case
id
}
}
Assume we have these lists:
<ItemsCell id={0} />
<ItemsCell id={1} search={"foo"} />
and I am adding new item to id 1 with refetchQueries like this:
refetchQueries: {
query: QUERY,
variables: {
id: 1,
search: 'bar'
}
}
This triggers a fetch of the query on the backend, but my component won’t rerender. And I am wondering if the reason is the difference in the search parameter, so equality checks won’t find the right ItemsCell. Is this assumption correct?
Now my approaches would be, to either use apollo cache (complex) or expose a refetch function of the ItemsCell in a global state.
React may need a key to know which cell is getting which query in order to update now that there are multiple cells.
I would also say to embrace the cache though! It saves you a network trip as well as saves if the query was expensive.
I go back to this video to reference setting up cache:
They go through the refetchQueries part to start, but using update can basically allow you to know the backend is updated and just manually update the cache locally instead of refetching the whole group again.
const [upsertShipstationLineItems] = useMutation(UPSERT_LINE_ITEMS, {
onCompleted: () => {
toast({
title: 'Updated Items!',
description: 'Friday, February 10, 2023 at 5:57 PM',
})
},
update(cache, { data }) {
const existingData = cache.readQuery({
query: QUERY,
})
const newData = [
...data.upsertShipstationLineItems, // New data from the mutation
...(existingData ? existingData.shipstationLineItemsOfOrderNumber : []), // Existing data
]
cache.writeQuery({
query: QUERY,
data: {
// Merge the new data with the existing data
shipstationLineItemsOfOrderNumber: newData,
},
})
handleLineItemReportLoaded(newData)
},
})
this is an example I have where I add an Item to a list so I have to grab the existing items and spread to add in the new item in the cache.
A confusing part is that the cell’s Queries that are exported are all just called Query so I have to make sure I pulled the correct cell’s “QUERY”.
1 Like
Thanks a lot! Also for the thorough example! I am going to try to use the cache 
1 Like