How to use Apollo’s multiple useQuery() hooks in React

How to use Apollo’s multiple useQuery() hooks in React


2

I need to use 2 queries in my file and I am writing them like so:

const {loading, data } = useQuery(getCharactersQuery);
const {loading, data} = useQuery(getSingleCharacterQuery);

The problem is, they both have the same "loading" and "data" variables and I don’t see anywhere in the docs how can we have different ones. How can I differentiate them?

3 Answers
3


3

It’s Object destructuring of JS Destructuring assignment. You can choose not to use it here to give different variable names.

const resCharacters = useQuery(getCharactersQuery);
const resSingleCharacter = useQuery(getSingleCharacterQuery);

if (resCharacters.loading || resSingleCharacter.loading) return 'Loading...';
...


3

This way, by giving them an alias.

const {loading, data } = useQuery(getCharactersQuery);
const {loading: singleCharacterLoading, data: singleCharacterData} = useQuery(getSingleCharacterQuery);


-1

const GET_DATA = gql`
  query {
    characters {
      phone
      rating
      ratingType
      review
      city
      id
    }
    singleCharacter {
      title
      text
    }
  }
`;

const {loading, data } = useQuery(GET_DATA);

console.log(data) //{characters: [...], singleCharacter: [...]} 

2

  • The author specifically asked how to solve this when they need to use more than one query. Also, please explain your code / the idea behind it and why it solves the problem.

    – Taxel

    Sep 15, 2021 at 15:44

  • Obviously, the request goes to one database, so we can combine several requests into one.

    – Alan Kuper

    Sep 16, 2021 at 11:11



Leave a Reply

Your email address will not be published. Required fields are marked *