7

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

greg
  • 199
  • 2
  • 10
  • insert `debugger` and check if cache really contains these entries (don't trust dev tool) ... there is a difference between query and normalized type entries ... you're looking for `readFragment` ... why not simply use `useQuery` with `cache-only` field policy? – xadm Jun 06 '21 at 21:19

1 Answers1

10

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,
})
greg
  • 199
  • 2
  • 10
  • what if you only have the name and are looking for the id? I'm also always getting null – Damian Green Mar 25 '22 at 15:27
  • @DamianGreen in this case you may customize your key take a look at this official docs https://www.apollographql.com/docs/react/caching/cache-configuration#customizing-cache-ids – soldy Aug 11 '22 at 20:53