Subscribing to, selecting, and updating all records of a particular type, in the cache

Hi,

I’m creating a “select all” sort of checkbox, but I’m not sure how to interact with the cache in a way to implement it.

The checked field is a @client field, and updating one record at a time via writeFragment works great for that case, but it’s not clear to me how to do that for multiples. I only need to care about this local field for the feature I’m working on, which may or may not complicate things.

What is the correct way to handle something like this?

I seem to have found a workaround with a separate reactive var that just stores the checked status of each record, and using that to update component state as necessary. Seems kind of convoluted from a maintenance standpoint, though.

Hi, I would like to see some example code because I can’t quite wrap my head around what you’re trying to do. I might be able to help you out then. :slight_smile:

Sure. Here’s what I have right now. It’s a React hook. Basically I’m both writing to the cache, and updating a reactive variable. So far it works fine, though I’m super-concerned about keeping things in sync.

export const useSelectAll = () => {
  const client = useApolloClient();

  return (selected) => {
    const { cache } = client;

    Object.values(cache.data?.data || {}).forEach((value) => {
      // eslint-disable-next-line no-underscore-dangle
      if (value.__typename === Shot.entityType()) {
        selectedShotIds({
          ...selectedShotIds(),
          [value.id]: selected
        });

        writeSelectedFragment(value.id, selected, client);
      }
    });
  };
};

To be honest, I would probably do it very similarly. Two points:

  1. What do you need the reactive variable for? As I understood it, checked (or selected) is a @client field, so you have that information right there on your cache objects. Wouldn’t using a reactive variable duplicate that information in this case?
  2. I’d suggest using cache.extract() rather than cache.data?.data. It’s the same thing but has the advantage of using the official API.

The reactive var is so the component that actually implements the “select all” checkbox can know when it has to check/uncheck itself, when you interact with the per-record checkboxes.