HomeAbout

useQuery

What is useQuery

Hooks provided by Apollo that can be called by a component.

  • Hook triggers the query.

When React mounts and renders a component that calls the useQuery hook, Apollo client automatically executes the specified query.

const { loading, error, data } = useQuery(GET_DATA, { variables: { dataId }, });

What is useLazyQuery

useLazyQuery hook executes query in response to events other than component rendering.

  • When useLazyQuery is called, it doesn't immediately execute the associated query, it returns a function in tuple that you can call at the right point in time the query needs to be called.
import React, {useState} from "react"; import {useLazyQuery} from "@apollo/client"; function DelayedQuery() { const [dog, setDog] = useState(null); const [getDog, {loading, data}] = useLazyQuery(GET_DOG_QUERY); if(loading) return <p>loading...</p>; if(data && data.result) { setDog(data.result); } return ( <> {dog && <div>{dog}</div>} <button onClick={() => getDog({variables: {type: 'someType'}})}> {"Click to trigger query"} </button> </> ) }
AboutContact