jas305
jas305

Reputation: 99

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

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?

Upvotes: 3

Views: 3283

Answers (3)

Alan Kuper
Alan Kuper

Reputation: 26

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: [...]} 

Upvotes: -1

keikai
keikai

Reputation: 15146

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...';
...

Upvotes: 4

jperl
jperl

Reputation: 5112

This way, by giving them an alias.

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

Upvotes: 3

Related Questions