Fluent Commerce Logo
Docs
Sign In

Fetching Data with the useQuery Hook

Essential knowledge

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`
hook. We'll move away from relying on page query data and instead directly query the Fluent GraphQL API to retrieve a list of nearby locations with product stock. This involves defining data structures for query results, storing the query in a constant, and using the
`useQuery`
hook to execute the query with dynamic parameters derived from the form's context and the user's context (via
`useAuth`
). We will then render the results in a selectable list using radio buttons.

Key points

  • Data Independence: Components should fetch their own data using the
    `useQuery`
    hook, rather than relying on potentially unavailable page query data.
  • GraphQL Query: A GraphQL query (
    `searchVirtualInventory`
    ) is used to retrieve nearby locations with stock.
  • Data Structures: Interfaces (SVINode, SVIResult) are defined to structure the query results.
  • `useQuery`
    Hook: The
    `useQuery`
    hook is used to execute the GraphQL query with dynamic parameters.
  • Dynamic Parameters: Query parameters (
    `productRef`
    ,
    `locationRef`
    ,
    `lat`
    ,
    `lng`
    ) are derived from the form's entity context (product) and the user's context (location) using the
    `useAuth`
    hook.
  • 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
    `useQuery`
    hook to pass in the parameters and execute the query

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`
, and
`lng`
as input variables.

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
    `useQuery`
    hook [0:52] to pass in the parameters [1:45] and execute the query.  

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
    `productRef`
    from the
    `entityContext`
    on 
    `FormFieldProps`
    , which is the current Product we're performing the availability lookup on [2:22]
  • Retrieve the
    `locationRef`
    ,
    `lat`
    and
    `lng`
    from the currently logged-in user's context, using the
    `useAuth`
    hook. [3:08]
  • 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
    `FormControlLabel`
    from the standard Material UI component library [1:06]
  • Set the checked radio property to the result that matches the state variable location [1:30]
  • Add an
    `onChange`
    handler to update the
    `location`
    state variable [1:54]
  • To confirm it works, add another console log to the
    `useEffect`
    hook to print out the currently selected
    `location`
    state variable value [2:42]

Using Query Data

This video explains how to make use of query data obtained from the component