Given the following React component using useQuery from Apollo Client, what will be the value of data after the query completes successfully?
import { useQuery, gql } from '@apollo/client'; const GET_USERS = gql` query GetUsers { users { id name } } `; function UsersList() { const { loading, error, data } = useQuery(GET_USERS); if (loading) return 'Loading...'; if (error) return `Error! ${error.message}`; return data; }
Think about what the data object contains after a successful query.
The useQuery hook returns an object where data holds the result of the GraphQL query. After success, data contains the queried fields, here the list of users.
Which option contains correct syntax when using useQuery?
const { loading, error, data } = useQuery(GET_POSTS, { variables: { id: 1 } });
Check the syntax of the options object passed to useQuery.
The options object must be wrapped in curly braces with key-value pairs. Option D correctly wraps variables in an object. Other options have syntax errors like missing braces or wrong assignment.
You want to avoid re-fetching data when the component re-renders but the variables haven't changed. Which option correctly achieves this?
Think about which fetch policy uses cached data first to avoid network calls.
The cache-first policy returns cached data if available and only fetches from the network if not cached, preventing unnecessary network requests on re-renders.
Consider this React component:
function MyComponent() {
const { data } = useQuery(GET_ITEMS, { variables: { filter: getFilter() } });
return <div>{data?.items.length}</div>;
}
function getFilter() {
return { active: true };
}Why does this cause an infinite loop of queries?
Think about how React compares objects in dependencies.
Each render calls getFilter() which returns a new object reference. This makes variables change every time, causing useQuery to re-fetch endlessly.
In the useQuery hook, what does the loading property indicate?
Consider the lifecycle of a query request.
The loading flag is true while the query is fetching data. It becomes false when the data is received or an error occurs.