Apollo readQuery, get data from cache
Asked Answered
T

1

8

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

Theodora answered 6/6, 2021 at 21:8 Comment(1)
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?Hopfinger
T
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,
})
Theodora answered 7/6, 2021 at 10:39 Comment(2)
what if you only have the name and are looking for the id? I'm also always getting nullMizzle
@DamianGreen in this case you may customize your key take a look at this official docs apollographql.com/docs/react/caching/…Mangosteen

© 2022 - 2024 — McMap. All rights reserved.