Leverage Apollo Cache

68 Views Asked by At

When upgrading to Apollo client 3.3, we decided to enable the caching in order to reduce network traffic and save computation power. We tried to implement something like this :

cache: new InMemoryCache({   typePolicies: {
    VegaSpecification: {
      keyFields: ["reportID"]
    },
    Query: {
      fields: {
        report: {
          merge: true
        }
      }
    }   } })

However, the caching implemented in Apollo does not fit our datastructure and therefore we receive incorrect results.

First we query the report with filter a. We do not have any data in cache for that query and therefore we hit the backend and receive

{ 
   _id: "initialReportId",
   vegaspecification: {
     reportID: "initialReportId",
     data: "data for a"
   }
}

In the cache apollo automatically stores:

Report: {
  _id: "initialReportId",
  vegaspecification: {
     "__ref":"VegaSpecification: {"reportID":"initialReportId"}"
  }
}
VegaSpecification: { 
  reportID: "initialReportId",
  data: "data for a"
}

Then we query the report with filter b. We again have no data for that query in the cache and hit the backend and receive

{
  _id: "initialReportId",
  vegaspecification: {
    reportID: "initialReportId",
    data: "data for b"
  }
}

In the cache we update

Report: {
  _id: "initialReportId",
  vegaspecification: {
     "__ref":"VegaSpecification:{"reportID":"initialReportId"}"
  }
}
VegaSpecification: {
  reportID: "initialReportId",
  data: "data for b"
}

When we query the report for filter a again the cache is accessed as there is already a query existing:

Report: {
  _id: "initialReportId",
  vegaspecification: {
     "__ref":"VegaSpecification:{"reportID":"initialReportId"}"
  }
}

Then the reference to the VegaSpecification is resolved - returning

VegaSpecification: {
  reportID: "initialReportId",
  data: "data for b"
}

Therefore we return the incorrect data for the filter a. We use "useMemo" to recompute the memoized values.

How can we structure our entities such that for different queries with different query variables we receive results that are distinguishable by an id

0

There are 0 best solutions below