React-apollo: Multiple queries which depend on each other

Created on 24 Oct 2019  ·  1Comment  ·  Source: apollographql/react-apollo

Intended outcome:
I would like to be able to execute multiple queries that depend on one another. For example:

const { loading, error, data: user } = useQuery(GET_USER);

const { loading: loadingProfile, data: userPorfile } = useQuery(GET_USER_PROFILE, { 
  variables: { id: user.id } 
});

Actual outcome:
It throws an error since user is undefined

How to reproduce the issue:

  • Try execute two queries where the second one depends on the first one.

    Version
    "react-apollo": "3.1.3"

    Other
    I have found some information on spectrum and current suggestion with using default cache is not great for me since we have multiple queries in a lot of places in cache default will become difficult to maintain.

    What is the best way to handle this?

    Thanks in advance and keep up the good work!

Most helpful comment

I would pass the skip option into the second query like this:

const { loading, error, data: user } = useQuery(GET_USER);

const { loading: loadingProfile, data: userProfile } = useQuery(GET_USER_PROFILE, { 
  variables: { id: user && user.id },
  skip: user == null 
});

This tells the second query to not request anything until the user data is available.

>All comments

I would pass the skip option into the second query like this:

const { loading, error, data: user } = useQuery(GET_USER);

const { loading: loadingProfile, data: userProfile } = useQuery(GET_USER_PROFILE, { 
  variables: { id: user && user.id },
  skip: user == null 
});

This tells the second query to not request anything until the user data is available.

Was this page helpful?
0 / 5 - 0 ratings