Fetching Data with the useQuery Hook
Authors:
Cameron Johns, Cille Schliebitz, Anita Gu
Changed on:
3 Feb 2025
Overview
This lesson focuses on fetching data within a custom form field using the
`useQuery`
`useQuery`
`useAuth`
Key points
- Data Independence: Components should fetch their own data using the hook, rather than relying on potentially unavailable page query data.
`useQuery`
- GraphQL Query: A GraphQL query () is used to retrieve nearby locations with stock.
`searchVirtualInventory`
- Data Structures: Interfaces (SVINode, SVIResult) are defined to structure the query results.
- Hook: The
`useQuery`
hook is used to execute the GraphQL query with dynamic parameters.`useQuery`
- Dynamic Parameters: Query parameters (,
`productRef`
,`locationRef`
,`lat`
) are derived from the form's entity context (product) and the user's context (location) using the`lng`
hook.`useAuth`
- Loading State: A loading state is implemented while the query progresses.
- Result Rendering: The query results are initially logged to the console and then rendered as a list of selectable locations using radio buttons.
- User Selection: A state variable and event handler are used to track the user's selected location.
To retrieve a list of locations with stock close by (using the SearchVirtualInventory query), you will need to perform the following steps:
- Define a structure for the SearchVirtualInventory query result nodes
- Define a structure for SearchVirtualInventory results
- Store the query in a string constant
- Use the hook to pass in the parameters and execute the query
`useQuery`
First, define a structure for the SearchVirtualInventory query result nodes:
`interface SVINode {`
` location: { name: string; ref: string };`
` virtualPositions: Array;`
`}`
Next, define a structure for SearchVirtualInventory results:
`interface SVIResult {`
` searchVirtualInventory: Connection;`
`}`
Store the query in a string constant:
1const searchVirtualInventoryQuery = `query availability($productRef: String!, $locationRef: String!, $lat: Float!, $lng: Float!) {
2 searchVirtualInventory(
3 virtualCatalogue: { ref: "VC:ATS:CC:1" },
4 productQuantities: [{ productRef: $productRef, quantity: 1 }],
5 excludedLocationRefs: [$locationRef],
6 orderByProximity: { longitude: $lng, latitude: $lat }
7 ) {
8 edges {
9 node {
10 location { ref name }
11 virtualPositions { quantity }
12 }
13 }
14 }
15 }`;
Language: plain_text
Name: searchVirtualInventoryQuery
Description:
This string constant stores the GraphQL query used to fetch virtual inventory data. The query retrieves a list of locations that stock a specific product, excluding the current location, and orders the results by proximity to a given latitude and longitude. It takes
`productRef`
`locationRef`
`lat`
`lng`
Refer to the video below to complete the remaining steps:
- Add the entityContext property to your component props [0:33], and call the useAuth hook [0:39]. We will retrieve values from each of these later when setting the query parameter values.
- Use the hook [0:52] to pass in the parameters [1:45] and execute the query.
`useQuery`
Each Form has context information about the entity or entities being updated. This form is generated based on a User Action defined a Product Ruleset within the Product Catalogue workflow, and therefore has context of the Product entity.
- Retrieve the from the
`productRef`
on`entityContext`
, which is the current Product we're performing the availability lookup on [2:22]`FormFieldProps`
- Retrieve the ,
`locationRef`
and`lat`
from the currently logged-in user's context, using the`lng`
hook. [3:08]`useAuth`
- Since the query will be executed asynchronously, it is best practice to show a "Loading" component in the UI until the query results are returned and can be rendered. [4:37]
- Once the results are returned by the query, they can be rendered to screen. For now, we'll print out the JSON response. [5:01]
Fetching data in a component
This video explains how to fetch data from a component using a useQuery hook
Now that our query is returning data, we need to present a list for the user to select a specific location.
Watch the following video to complete to steps below:
- Add a new state variable for the location [0:10]. This will be updated each time the user selects a different location.
- Loop through the results and render a radio button and label for each result [0:44] — for this, use the from the standard Material UI component library [1:06]
`FormControlLabel`
- Set the checked radio property to the result that matches the state variable location [1:30]
- Add an handler to update the
`onChange`
state variable [1:54]`location`
- To confirm it works, add another console log to the hook to print out the currently selected
`useEffect`
state variable value [2:42]`location`
Using Query Data
This video explains how to make use of query data obtained from the component