usequery react code example
Example 1: variables in useQuery apollo
const GET_DOG_PHOTO = gql`
query Dog($breed: String!) {
dog(breed: $breed) {
id
displayImage
}
}
`;
function DogPhoto({ breed }) {
const { loading, error, data } = useQuery(GET_DOG_PHOTO, {
variables: { breed },
});
if (loading) return null;
if (error) return `Error! ${error}`;
return (
<img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />
);
}
Example 2: useLazyQuery
import React, { useState } from 'react';
import { useLazyQuery } from '@apollo/client';
function DelayedQuery() {
const [dog, setDog] = useState(null);
const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);
if (loading) return <p>Loading ...</p>;
if (data && data.dog) {
setDog(data.dog);
}
return (
<div>
{dog && <img src={dog.displayImage} />}
<button onClick={() => getDog({ variables: { breed: 'bulldog' } })}>
Click me!
</button>
</div>
);
}
Example 3: appolo client variables pass
const query = gql`
query User($okta: String) {
User(okta: $okta){
id
}
}
`;
client.query({
query: query,
variables: {
okta: 'some string'
}
})
Example 4: apoolo uselaxyQuery bypass cache
const { data: cachedData } = useQuery(MyQuery, { fetchPolicy: 'cache-only', variables });
const [executeMyQuery, { data: queryData, loading, error }] = useLazyQuery(MyQuery, {
fetchPolicy: 'network-only'
});
const data = queryData || cachedData;