Apollo 2: Variables & Dynamic Queries
easy⏱ 5 mincourseapollo
Passing variables to queries
GraphQL queries accept variables — named parameters prefixed with $. In Apollo, pass them via the variables option: useQuery(SEARCH_USERS, { variables: { term } }). When the variable changes, Apollo automatically re-executes the query (or serves from cache if available). Variables are type-safe in your schema: query Search($term: String!) ensures the server validates the input.
const SEARCH_USERS = gql`
query SearchUsers($term: String!) {
searchUsers(term: $term) {
id
name
email
}
}
`;
function Search() {
const [term, setTerm] = useState('');
const { loading, data } = useQuery(SEARCH_USERS, {
variables: { term },
skip: term.length < 2,
});
}
Build a search with variables
Create a SEARCH_USERS query that takes a $term: String! variable. Use useState to track the search input. Pass the term via variables: { term } in your useQuery call. Add skip: term.length < 2 so the query only fires when the user has typed at least 2 characters. Display results in a list.
previousData for smooth UX
When variables change, data becomes undefined while the new query loads. Use the previousData field from useQuery to keep showing the old results: const { data, previousData } = useQuery(...). Render data ?? previousData to avoid the UI flashing blank between searches.
const { data, previousData, loading } = useQuery(SEARCH_USERS, {
variables: { term },
});
const displayData = data ?? previousData;
skip for conditional execution
The skip option prevents a query from executing. Unlike wrapping in a conditional, skip keeps the hook call unconditional (React rules of hooks). Common pattern: skip: !selectedId or skip: searchTerm.length < 3. The query will automatically execute when skip becomes false.