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
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...';
...
- Ref: Apollo document of useQuery
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.
– TaxelSep 15, 2021 at 15:44
-
Obviously, the request goes to one database, so we can combine several requests into one.
– Alan KuperSep 16, 2021 at 11:11