greg
greg

Reputation: 219

Apollo readQuery, get data from cache

I'm trying to get data from Apollo cache. I know that data is there because in Apollo dev tools specified records are available. In my react app I making a simple click and set Id which later passes to the query. Result from client.readQuery(...) is null. I'm spinning around because don't know why. I'm using code exactly the same way as in docs.

Here's a QUERY:

export const RECRUIT_QUERY = gql`
  query Recruit($id: ID!) {
    Recruit(_id: $id) {
      _id
      firstName
    }
  }
`;

Usage of apollo hooks in component:

const client = useApolloClient();
const recruit = client.readQuery({
  query: RECRUIT_QUERY,
  variables: { id: selectedId }
})

Configuration of apollo:

export const client = new ApolloClient({
  link: concat(
    authMiddleware,
    new HttpLink({
      uri: process.env.REACT_APP_API_URL,
    }),
  ),
  cache: new InMemoryCache(),
});

Here's apollo store preview: enter image description here

Upvotes: 8

Views: 9733

Answers (1)

greg
greg

Reputation: 219

Using readFragment covers my expectation. previously I have tried this solution but wrongly, ex:

 client.readFragment({
   id: '4587d3c2-b3e7-4ade-8736-709dc69ad31b',
   fragment: RECRUIT_FRAGMENT,
 });

In fact Appollo store cound't find this record. Correct solution looks like this:

client.readFragment({
  id: 'Recruit:4587d3c2-b3e7-4ade-8736-709dc69ad31b',
  fragment: RECRUIT_FRAGMENT,
})

Upvotes: 10

Related Questions