Given below is the query that fetches a list of products and stores it in the apollo-client local cache. It retrieves a list of products
and the list of images
for every product
const GET_PRODUCTS_QUERY = gql`
query Products($cursor: String, $query: String, $imageCount: Int = 100) {
products(first: 9, after: $cursor, query: $query) {
edges {
cursor
node {
id
selected @client
title
description
images(first: $imageCount) {
edges {
node {
id
originalSrc
selected @client
}
}
}
}
}
}
}
`;
The data returned is being used to render a UI where the user can select any number of products. I'm using the following mutation to mark a product as selected
(_root, variables, { getCacheKey, cache }) => {
const id = getCacheKey({
__typename: "Product",
id: variables.id
});
const fragment = gql`
fragment toggleSelected on Product {
selected,
}
`;
const data = cache.readFragment({
id,
fragment
});
cache.writeData({
id,
data: {
...data,
selected: !data.selected
}
});
The above mutation is working fine and the selected
flag appears on the corresponding product
in the cache. Now I have the requirement that when a product is selected, it's first image should also be marked as selected without any manual action from the user. In this case, I do not have the id of the image with me. I just know that whatever be the first image of the selected product, it should be marked as selected. How can I go about achieving this? If I had the id, I guess I will be able to create a fragment on the Image object and get it mutated.