0
votes

Perhaps I am just not getting what apollo-link-state does, but I figured if I had a "default" value, THAT would show up in my props via the Provider. Yet, I can't locate it. How do you access the "cache" or local state?

I have:

import { ApolloClient, createNetworkInterface } from 'react-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';
import dataIdFromObject from './dataIdFromObject';

const defaults = {
  NAME: 'Biff'
};
const resolvers = {};

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

const apolloClient = new ApolloClient({
  cache,
  link: stateLink,
  networkInterface: createNetworkInterface({
    uri: `${config.url}/graphql`,
    opts: {
      credentials: 'include'
    }
  }),
  addTypename: true,
  dataIdFromObject
});

I am passing in an empty object for my resolvers as it absolutely makes no sense to replicate all of reducers that are in the backend. I figured that I'd see the "name: Biff" in the props. Nope.

The store is my "redux" store and is not part of this question. I figured with that "client" prop, I'd see my default. Nope.

  <ApolloProvider store={this.props.store} client={apolloClient}>

when I log my props in a child component, no sign of cache or "name: Biff" anywhere. How do I get at this local state in my child components. If I update it with a mutation, I should see my components rerender and having access to that new updated local state...but.. where is it?

1
On a related note, you may want to revisit the latest docs and update your versions of apollo-client and react-apollo. ApolloProvider no longer takes store as a prop and does not depend on a redux store, period. That's what the InMemoryCache is for. Similarly, links have replaced createNetworkInterface. You shouldn't even be able to import that if you were using version 2.0Daniel Rearden
weird, because I do have v2+. I'll look up the additional requirements.james emanon

1 Answers

1
votes

As outlined in the docs, you query your local state just like you query a remote server, except you tack on a @client directive to let Apollo know that you're requesting something through apollo-link-state. So we need a GraphQL query, wrapped with a graphql-tag template literal tag:

const GET_NAME = gql`
  query {
    NAME @client
  }
`

And we use it just like any other query:

<Query query={GET_NAME}>
  {({ loading, error, data }) => {
    // render appropriate component depending on loading/error state
  }}
</Query>

While Apollo exposes methods for reading and writing to the cache, these should only be used in the context of creating mutations for your local state. Querying the cache should be done through the Query component and actually mutating the cache should be done through the Mutation component. You can read more about writing your own mutations in the docs.