Ad

Apollo Client State - Object Written To Cache With WriteData Is Missing

I have a problem with Apollo Client State in my React app. I'm creating my client state link in the following way:

const stateLink = withClientState({
  cache,
  defaults: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
    pageTitle: null,
  },
  resolvers: {},
});

At some point I have to clear cache in the application (after logout) which also clears my client state. I'm clearing the cache in this way:

client.resetStore()

Where client is obtained by using withApollo HOC. After that I'm trying to recreate my local state with the following calls:

client.writeData({
  data: {
    pageTitle: 'test',
  },
});

client.writeData({
  data: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
  },
});

But it doesn't work - only pageTitle is stored in the cache which results in failure in all client state simulation-related queries.

Cache before clearing:

{
  "data": {
    "$ROOT_QUERY.simulation": {
      "__typename": "Simulation",
      "configurationName": null,
      "job": null,
      "status": null,
      "uuid": null
    },
    "ROOT_QUERY": {
      "simulation": {
        "type": "id",
        "generated": true,
        "id": "$ROOT_QUERY.simulation",
        "typename": "Simulation"
      },
      "pageTitle": null
    }
  }
}

Cache after clearing and restoring local state:

{
  "data": {
    "ROOT_QUERY": {
      "pageTitle": null
    }
  }
}

Instead of second writeData I've also tried writing query:

const SIMULATION_LOCAL_DATA_QUERY = gql`
  {
    simulation @client {
      configurationName
      job
      status
      uuid
    }
  }
`;

client.writeQuery({
  query: SIMULATION_LOCAL_DATA_QUERY,
  data: {
    simulation: {
      __typename: 'Simulation',
      configurationName: null,
      job: null,
      status: null,
      uuid: null,
    },
  },
});

But it also didn't work. Could somebody tell me what am I doing wrong? Thanks!

Ad

Answer

Taking a look through the docs, the suggested method for resetting the store after a client logout is to use the writeDefaults method, which you can inject as a callback on the onRestStore method:

const cache = new InMemoryCache();
const stateLink = withClientState({ cache, resolvers, defaults });

const client = new ApolloClient({
  cache,
  link: stateLink,
});

const unsubscribe = client.onResetStore(stateLink.writeDefaults);

This comes straight from: https://www.apollographql.com/docs/link/links/state.html

Hope that helps.

Ad
source: stackoverflow.com
Ad