@gadgetinc/react 

The @gadgetinc/react package provides React hooks for calling your Gadget app's autogenerated API.

JavaScript
1import { useFindMany, useAction } from "@gadgetinc/react";
2import { api } from "../api"; // your app's autogenerated API client
3
4function WidgetDeleter() {
5 // `useFindMany` executes a backend fetch to get a list of widgets from the backend.
6 const [{ data, fetching, error }, refresh] = useFindMany(api.widget, {
7 select: {
8 id: true,
9 name: true,
10 },
11 });
12
13 // `useAction` sets up a mutation we can run to delete a specific widget when a user clicks a button
14 const [_, deleteWidget] = useAction(api.widget.delete);
15
16 if (fetching) return "Loading...";
17 return (
18 <ul>
19 {data.map((widget) => (
20 <li>
21 {widget.name}{" "}
22 <button onClick={() => deleteWidget({ id: widget.id })}>Delete</button>
23 </li>
24 ))}
25 </ul>
26 );
27}

Key features 

  1. Rule-obeying hooks for reading and writing data from a backend that handle all request lifecycle and auth like useFindOne, useAction, and useFetch
  2. Full type safety for inputs and outputs driven by each Gadget app's backend schema, including over dynamic selections
  3. A full-featured, GraphQL-powered nested object selection system using the select option
  4. Data hydrations that return useful objects like Dates

Installation 

See the installation instructions for your app's API.

Provider Setup 

Your React application must be wrapped in the Provider component from this library for the hooks to function properly. No other wrappers (like urql's) are necessary.

Gadget provisions applications with the required <Provider /> component already in place! If using the frontend hosting built into Gadget, no action is required as this step is already done.

Example:

JavaScript
1// import the API client for your specific application from your client package, be sure to replace this package name with your own
2import { Client } from "@gadget-client/example-app-slug";
3// import the required Provider object and some example hooks from this package
4import { Provider } from "@gadgetinc/react";
5
6// instantiate the API client for our app
7const api = new Client({ authenticationMode: { browserSession: true } });
8
9export const MyApp = (props) => {
10 // wrapp the application in the <Provider> so the hooks can find the current client
11 return <Provider api={api}>{props.children}</Provider>;
12};

Hooks 

useFindOne() 

useFindOne(manager: ModelFinder, id: string, options: SingleFinderOptions = {}): [{data, fetching, error}, refetch]

useFindOne fetches one record from your Gadget database with a given id.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const ShowWidgetName = (props) => {
5 const [{ data, fetching, error }, _refetch] = useFindOne(api.widget, props.id);
6
7 if (fetching) return "Loading...";
8 if (error) return `Error loading data: ${error}`;
9 return <span className="widget-name">{data.name}</span>;
10};
Parameters 
  • manager: The model manager you for the model you want to find a record of. Required. Example: api.widget, or api.shopifyProduct
  • id: The backend id of the record you want to find. Required.
  • options: Options for making the call to the backend. Not required, and all keys are optional.
    • select: A list of fields and subfields to select. See Select option
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Set to true to disable this hook. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense
Returns 

useFindOne returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and a refetch function to trigger a refresh of the hook's data.

  • data: GadgetRecord | null: The record fetched from the backend. Is null while the data is being loaded, or if the record wasn't found.
  • fetching: boolean: A boolean describing if the hook is currently requesting data from the backend.
  • error: Error | null: An error from the client or server side, if encountered during the request. Will contain an error if the record isn't found by id. See the Errors section.

useFindOne expects a record with the given id to be found in the backend database, and will return an error in the error property if no record with this id is found.

useFindOne can select only some fields from the backend model with the select option:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const OnlySomeWidgetFields = (props: { id: string }) => {
5 // fetch only the widget id and name fields
6 const [{ data, fetching, error }, _refetch] = useFindOne(api.widget, props.id, {
7 select: { id: true, name: true },
8 });
9
10 return (
11 <span className="widget-name">
12 {data?.id}: {data?.name}
13 </span>
14 );
15};

useMaybeFindOne() 

useMaybeFindOne(manager: ModelFinder, id: string, options: SingleFinderOptions = {}): [{data, fetching, error}, refetch]

useMaybeFindOne fetches one record from your Gadget database with a given id.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const ShowWidgetName = (props) => {
5 const [{ data, fetching, error }, _refetch] = useMaybeFindOne(
6 api.widget,
7 props.id
8 );
9
10 if (fetching) return "Loading...";
11 if (error) return `Error loading data: ${error}`;
12 if (data) {
13 return <span className="widget-name">{data.name}</span>;
14 } else {
15 return "No widget found";
16 }
17};

useMaybeFindOne will return data: null and error: null if no record with the given id is found in the backend database. useMaybeFindOne otherwise behaves identically to useFindOne, and accepts the same options.

useFindMany() 

useFindMany(manager: ModelFinder, options: ManyFinderOptions = {}): [{data, fetching, error}, refetch]

useFindMany fetches a page of records from your Gadget database, optionally sorted, filtered, or searched.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const ShowWidgetNames = () => {
5 const [{ data, fetching, error }, _refetch] = useFindMany(api.widget);
6
7 if (fetching) return "Loading...";
8 if (error) return `Error loading data: ${error}`;
9 return (
10 <ul>
11 {data.map((widget) => (
12 <li key={widget.id}>{widget.name}</li>
13 ))}
14 </ul>
15 );
16};
Parameters 
  • manager: The model manager you for the model you want to find a page of records for. Required. Example: api.widget, or api.shopifyProduct
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • select: A list of fields and subfields to select. See the Select option docs.
    • filter: A list of filters to limit the set of returned records. Optional. See the Model Filtering section in your application's API documentation to see the available filters for your models.
    • search: A search string to match backend records against. Optional. See the Model Searching section in your application's API documentation to see the available search syntax.
    • sort: A sort order to return backend records by. Optional. See the Sorting section in your application's API documentation for more info.
    • first & after: Pagination arguments to pass to fetch a subsequent page of records from the backend. first should hold a record count and after should hold a string cursor retrieved from the pageInfo of the previous page of results. See the Model Pagination section in your application's API documentation for more info.
    • last & before: Pagination arguments to pass to fetch a subsequent page of records from the backend. last should hold a record count and before should hold a string cursor retrieved from the pageInfo of the previous page of results. See the Model Pagination section in your application's API documentation for more info.
    • live: Should this hook re-render when data changes on the backend. See the Live option docs.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense for more info
Returns 

useFindMany returns two values: a result object with the data, fetching, and error keys for use in your React component's output, and a refetch function to trigger a refresh of the hook's data.

  • data: GadgetRecordList | null: The resulting page of records fetched from the backend for your model, once they've arrived
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the request. See the Errors section.

Without any options, useFindMany will fetch the first page of backend records sorted by id.

useFindMany accepts the select option to allow customization of which fields are returned:

JavaScript
1export const OnlySomeWidgetFields = (props: { id: string }) => {
2 // fetch only the widget id and name fields
3 const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
4 select: { id: true, name: true },
5 });
6
7 if (fetching) return "Loading...";
8 if (error) return `Error loading data: ${error}`;
9 return (
10 <ul>
11 {data.map((widget) => (
12 <li key={widget.id}>{widget.name}</li>
13 ))}
14 </ul>
15 );
16};

useFindMany accepts a filter option to limit which records are returned from the backend. For example, we can filter to return only widgets created since the start of 2022:

JavaScript
1// fetch only the widgets created recently
2const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
3 filter: {
4 createdAt: { greaterThan: new Date(2022, 01, 01) },
5 },
6});

See your app's API reference for more information on which filters are available on what models.

useFindMany accepts a sort option to change the order of the records that are returned. For example, we can sort returned widgets by the createdAt field:

JavaScript
1// return the most recently created widgets first
2const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
3 sort: {
4 createdAt: "Descending",
5 },
6});

useFindMany accepts a search option to limit the fetched records to only those matching a given search query. For example, we can search all the backend widgets for those matching the string "penny" in any searchable field:

JavaScript
// return the most recently created widgets first
const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
search: "penny",
});

See your app's API reference for more information on the search query syntax and which fields are searchable.

useFindMany accepts a live option to subscribe to changes in the backend data returned, which will trigger re-renders of your react components as that data changes. For example, we can show an up-to-date view of the first page of backend widgets:

JavaScript
// will update when new widgets are created or on-screen widgets are updated
const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
live: true,
});

useFindMany accepts pagination arguments for getting the second, third, etc page of results from the backend beyond just the first page. Gadget applications use Relay Cursor style GraphQL pagination, where a second page is fetched by asking for the next x many results after a cursor returned with the first page.

JavaScript
1// return the first 10 results after some cursor from somewhere else
2const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
3 first: 10,
4 after: "some-cursor-value",
5});
6
7// data is a GadgetRecordList object, which has extra properties for inquiring about the pagination state
8// the current page's start and end cursor are available for use to then make later requests for different pages
9data.endCursor; // => string, used for forward pagination, pass to the `after:` variable
10data.startCursor; // => string, used for backwards pagination, pass to the `before:` variable
11// data also reports if there are more pages for fetching
12data.hasNextPage; // => boolean, true if there is another page to fetch after the `endCursor`
13data.hasPreviousPage; // => boolean, true if there is another page to fetch before the `startCursor`

An easy way to do pagination is using React state, or for a better user experience, using the URL with whatever router system works for your application. We use React state to demonstrate pagination in this example:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const WidgetPaginator = () => {
5 // store the current cursor in the backend data
6 const [cursor, setCursor] = useState(null);
7
8 // pass the current cursor to the `after:` variable, telling the backend to return data after this cursor
9 const [{ data, fetching, error }, _refetch] = useFindMany(api.widget, {
10 first: 20,
11 after: cursor,
12 });
13
14 if (fetching) return "Loading...";
15 if (error) return `Error loading data: ${error}`;
16
17 return (
18 <>
19 <ul>
20 {data.map((widget) => (
21 <li key={widget.id}>{widget.name}</li>
22 ))}
23 </ul>
24 <button
25 onClick={() => {
26 // update the cursor, which will trigger a refetch of the next page and rerender with a new `data` object
27 setCursor(data.endCursor);
28 }}
29 disabled={!data.hasNextPage}
30 >
31 Next page
32 </button>
33 </>
34 );
35};

useFindFirst() 

useFindFirst(manager: ModelFinder, options: FindManyOptions = {}): [{data, fetching, error}, refetch]

useFindFirst fetches the first record from your backend Gadget database that matches the given filter, sort, and search.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const MostRecentPublishedPost = (props: { id: string }) => {
5 // request the first record from the backend where publishedAt is set and with the most recent publishedAt value
6 const [{ data, fetching, error }, _refetch] = useFindFirst(api.blogPost, {
7 filter: { publishedAt: { isSet: true } },
8 sort: { publishedAt: "Descending" },
9 });
10
11 if (fetching) return "Loading...";
12 if (error) return `Error loading data: ${error}`;
13 return (
14 <span className="banner">
15 Check out our most recent blog post titled {data.title}
16 </span>
17 );
18};
Parameters 
  • manager: The model manager you for the model you want to find a page of records for. Required. Example: api.widget, or api.shopifyProduct
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • select: A list of fields and subfields to select. See the Select option docs. Optional.
    • filter: A list of filters to find a record matching. Optional. See the Model Filtering section in your application's API documentation to see the available filters for your models.
    • search: A search string to find a record matching. Optional. See the Model Searching section in your application's API documentation to see the available search syntax.
    • sort: A sort order to order the backend records by. useFindFirst will only return the first record matching the given search and filter, so sort can be used to break ties and select a specific record. Optional. See the Sorting section in your application's API documentation for more info.
    • live: Should this hook re-render when data changes on the backend. See the Live option docs.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense for more info
Returns 

useFindFirst returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and a refetch function to trigger a refresh of the hook's data.

  • data: GadgetRecord | null: The record fetched from the backend. Is null while the data is being loaded, or if a matching record wasn't found.
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the request. Will contain an error if the first record isn't found. See the Errors section.

If no record is found matching the conditions, useFindFirst will return {data: null, error: new MissingDataError}.

Without any options, useFindFirst will fetch the first matching record and cause your component to rerender as the fetch happens and when the data or error arrives.

useFindFirst can only select some of the fields from the backend model with select:

JavaScript
1// fetch the first upside down widget, and only it's id and name fields
2const [{ data }] = useFindFirst(api.widget, {
3 filter: {
4 state: { equals: "upsideDown" },
5 },
6 select: {
7 id: true,
8 name: true,
9 },
10});

useFindFirst can subscribe to changes in the returned data from the backend with the live option, and re-render when the backend data changes:

JavaScript
1// fetch the first upside down widget, and re-render if it's data changes
2const [{ data }] = useFindFirst(api.widget, {
3 filter: {
4 state: { equals: "upsideDown" },
5 },
6 live: true,
7});

useFindBy() 

useFindBy(findFunction: ModelFindFunction, fieldValue: any, options: FindByOptions = {}): [{data, fetching, error}, refetch]

useFindBy fetches one record from your backend looked up by a specific field and value. useFindBy requires a by-field record finder like .findBySlug or .findByEmail to exist for your model, which are generated by adding a Unique Validations to a field.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4// get a slug from the URL or similar, and look up a post record by this slug
5export const PostBySlug = (props: { slug: string }) => {
6 const [{ data, fetching, error }, _refetch] = useFindBy(
7 api.blogPost.findBySlug,
8 props.slug
9 );
10
11 if (fetching) return "Loading...";
12 if (error) return `Error loading data: ${error}`;
13 return (
14 <>
15 <h2>{data.title}</h2>
16 <p>{data.body}</p>
17 </>
18 );
19};
Parameters 
  • findFunction: The model finder function from your application's API client for finding records by a specific field. Gadget generates these finder functions for the fields where they are available. Changes to your Gadget backend schema may be required to get these to exist. Required. Example: api.widget.findBySlug, or api.user.findByEmail.
  • fieldValue: The value of the field to search for a record using. This is which slug or email you'd pass to api.widget.findBySlug or api.user.findByEmail.
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • select: A list of fields and subfields to select. See the Select option docs.
    • live: Should this hook re-render when data changes on the backend. See the Live option docs.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense for more info
Returns 

useFindBy returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and a refetch function to trigger a refresh of the hook's data.

  • data: GadgetRecord | null: The record fetched from the backend. Is null while the data is being loaded, or if a matching record wasn't found for the given fieldValue.
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the request. Will contain an error if a matching record isn't found. See the Errors section.

If no record is found matching the conditions, then the returned object will have null for the data. useFindBy(api.widget.findByEmail, "[email protected]") is the React equivalent of api.widget.findByEmail("[email protected]")

Without any options, useFindBy will fetch the record with the given field value, and cause your component to rerender as the fetch happens and when the data or error arrives:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4// get a slug from the URL or similar, and look up a post record by this slug
5export const PostBySlug = (props: { slug: string }) => {
6 const [{ data, fetching, error }, _refetch] = useFindBy(
7 api.blogPost.findBySlug,
8 props.slug
9 );
10
11 if (fetching) return "Loading...";
12 if (error) return `Error loading data: ${error}`;
13 return (
14 <>
15 <h2>{data.title}</h2>
16 <p>{data.body}</p>
17 </>
18 );
19};

useFindBy can take options that allow the customization of which fields are returned:

JavaScript
1// fetch only a post id and title fields
2const [{ data, fetching, error }, _refetch] = useFindBy(
3 api.blogPost.findBySlug,
4 "some-slug",
5 { select: { id: true, title: true } }
6);

The refetch function returned as the second element can be executed in order to trigger a refetch of the most up to date data from the backend. See urql's docs on re-executing queries for more information.

useMaybeFindFirst() 

useMaybeFindFirst(manager: ModelFinder, options: FindManyOptions = {}): [{data, fetching, error}, refetch]

useMaybeFindFirst fetches the first record from your backend Gadget database that matches the given filter, sort, and search parameters.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const MostRecentPublishedPost = (props: { id: string }) => {
5 // request the first record from the backend where publishedAt is set and with the most recent publishedAt value
6 const [{ data, fetching, error }, _refetch] = useMaybeFindFirst(api.blogPost, {
7 filter: { publishedAt: { isSet: true } },
8 sort: { publishedAt: "Descending" },
9 });
10
11 if (fetching) return "Loading...";
12 if (error) return `Error loading data: ${error}`;
13 if (data) {
14 return (
15 <span className="banner">
16 Check out our most recent blog post titled {data.title}
17 </span>
18 );
19 } else {
20 // no first record found
21 return null;
22 }
23};

useMaybeFindFirst returns data: null if no record is found in the backend database, and otherwise works identically to useFindFirst. See useFindFirst for more details on the options useMaybeFindFirst accepts.

useAction() 

useAction(actionFunction: ModelActionFunction, options: UseActionOptions = {}): [{data, fetching, error}, refetch]

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const CreatePost = () => {
5 const [{ data, fetching, error }, createBlogPost] = useAction(api.blogPost.create);
6
7 return (
8 <button
9 onClick={() => {
10 createBlogPost({
11 title: "New post created from React",
12 });
13 }}
14 >
15 Create a post
16 </button>
17 );
18};

useAction is a hook for running a backend action on one record of a Gadget model. useAction must be passed an action function from an instance of your application's generated API client. Options:

Parameters 
  • actionFunction: The model action function from your application's API client for acting on records. Gadget generates these action functions for each action defined on backend Gadget models. Required. Example: api.widget.create, or api.user.update or api.blogPost.publish.
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • select: A list of fields and subfields to select. See the Select option docs.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense for more info
Returns 

useAction returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and a act function to actually run the backend action. useAction is a rule-following React hook that wraps action execution, which means it doesn't just run the action as soon as the hook is invoked. Instead, useAction returns a configured function that will actually run the action, which you need to call in response to some user event. The act function accepts the action inputs as arguments -- not useAction itself.

useAction's result will return the data, fetching, and error details for the most recent execution of the action.

  • data: GadgetRecord | null: The record fetched from the backend after a mutation. Is null while before the mutation is run and while it is currently ongoing.
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the mutation. Will contain an error if the client passed invalid data, if the server failed to complete the action, or if a network error was encountered. See the Errors section.

For example, we can create a button that creates a post when clicked, and then shows the post once it has been created:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const CreatePost = () => {
5 const [{ data, fetching, error }, createBlogPost] = useAction(api.blogPost.create);
6
7 // deal with all the states of the result object
8 if (fetching) return "Loading...";
9 if (error) return `Error loading data: ${error}`;
10
11 if (!data) {
12 return (
13 <button
14 onClick={() => {
15 createBlogPost({
16 title: "New post created from React",
17 });
18 }}
19 >
20 Create a post
21 </button>
22 );
23 } else {
24 return (
25 <>
26 <h2>{data.title}</h2>
27 <p>{data.body}</p>
28 </>
29 );
30 }
31};

We can also run actions on existing models by passing the id: in with the action parameters:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const UpdatePost = (props: { id: string }) => {
5 // invoke the `useAction` hook, getting back a result object and an action runner function every render
6 const [{ data, fetching, error }, updateBlogPost] = useAction(api.blogPost.update);
7 const [title, setTitle] = useState("");
8
9 if (fetching) return "Loading...";
10 if (error) return `Error loading data: ${error}`;
11
12 return (
13 <form
14 onSubmit={() => {
15 // pass the id of the blog post we're updating as one parameter, and the new post attributes as another
16 updateBlogPost({
17 id: props.id,
18 title,
19 });
20 }}
21 >
22 <label>Title</label>
23 <input
24 type="text"
25 value={title}
26 onChange={(event) => setTitle(event.target.value)}
27 />
28 <input type="submit">Submit</input>
29 </form>
30 );
31};

useAction can take options that allow the customization of which fields are returned on the acted-upon record:

JavaScript
1// fetch only a post id and title fields
2const [{ data, fetching, error }, _refetch] = useFindBy(
3 api.blogPost.findBySlug,
4 "some-slug",
5 { select: { id: true, title: true } }
6);

useGlobalAction() 

useGlobalAction(actionFunction: GlobalActionFunction, options: UseGlobalActionOptions = {}): [{data, fetching, error}, refetch]

useGlobalAction is a hook for running a backend Global Action.

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const PurgeData = () => {
5 const [{ data, fetching, error }, runPurge] = useGlobalAction(api.purgeData);
6
7 return (
8 <button
9 onClick={() => {
10 purgeData({ foo: "bar" });
11 }}
12 >
13 Purge data
14 </button>
15 );
16};
Parameters 
  • globalActionFunction: The action function from your application's API client. Gadget generates these global action functions for each global action defined in your Gadget backend. Required. Example: api.runSync, or api.purgeData (corresponding to Global Actions named Run Sync or Purge Data).
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
Returns 

useGlobalAction returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and an act function to actually run the backend global action. useGlobalAction is a rule-following React hook that wraps action execution, which means it doesn't just run the action as soon as the hook is invoked. Instead, useGlobalAction returns a configured function which you need to call in response to some event. This act function accepts the action inputs as arguments. useGlobalAction's result will return the data, fetching, and error details for the most recent execution of the action.

  • data: Record&lt;string, any&gt; | null: The data returned by the global action from the backend. Is null while before the mutation is run and while it is currently ongoing.
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the mutation. Will contain an error if the client passed invalid data, if server failed to complete the mutation, or if a network error was encountered. See the Errors section.

For example, we can create a button that runs a Global Action called purgeData when clicked, and shows the result after it has been run:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const PurgeData = () => {
5 const [{ data, fetching, error }, runPurge] = useGlobalAction(api.purgeData);
6
7 // deal with all the states of the result object
8 if (fetching) return "Loading...";
9 if (error) return `Error running global action: ${error}`;
10
11 if (!data) {
12 return (
13 <button
14 onClick={() => {
15 purgeData({ foo: "bar" });
16 }}
17 >
18 Purge data
19 </button>
20 );
21 } else {
22 return "Purge completed";
23 }
24};

useGet() 

useGet(singletonModelManager: SingletonModelManager, options: GetOptions = {}): [{data, fetching, error}, refetch]

useGet fetches a singleton record for an api.currentSomething style model manager. useGet fetches one global record, which is most often the current session.

If you'd like to access the current session on the frontend, use the useSession() hook

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const CurrentSessionId = () => {
5 const [{ data, fetching, error }, _refetch] = useGet(api.currentSession);
6
7 if (fetching) return "Loading...";
8 if (error) return `Error loading data: ${error}`;
9 return (
10 <span>
11 Current session: {data.id} is {data.state}
12 </span>
13 );
14};
Parameters 
  • singletonModelManager: The singleton model manager available on the generated API client for your application. The passed model manager must be one of the currentSomething model managers. useGet can't be used with other model managers that don't have a .get function. Example: api.currentSession.
  • options: Options for making the call to the backend. Not required and all keys are optional.
    • select: A list of fields and subfields to select. See the Select option docs.
    • requestPolicy: The urql request policy to make the request with. See urql's docs
    • pause: Should the hook make a request right now or not. See urql's docs
    • suspense: Should this hook suspend when fetching data. See Suspense for more info
Returns 

useGet returns two values: a result object with the data, fetching, and error keys for inspecting in your React component's output, and a refetch function to trigger a refresh of the hook's data.

  • data: GadgetRecord | null: The record fetched from the backend. Is null while the data is being loaded, or if the record wasn't found.
  • fetching: boolean: A boolean describing if the hook is currently making a request to the backend.
  • error: Error | null: An error from the client or server side, if encountered during the request. Will contain an error if the singleton record isn't found. See the Errors section.

useGet(api.currentSession) retrieves the current global session for the current browser

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const CurrentSessionId = () => {
5 const [{ data, fetching, error }, _refetch] = useGet(api.currentSession);
6
7 if (fetching) return "Loading...";
8 if (error) return `Error loading data: ${error}`;
9 return (
10 <span>
11 Current session: {data.id} is {data.state}
12 </span>
13 );
14};

useGet can take options which allow the customization of which fields are returned on the selected record:

JavaScript
// fetch only the session id and state fields
const [{ data, fetching, error }, _refetch] = useGet(api.currentSession, {
select: { id: true, state: true },
});

The refetch function returned as the second element can be executed to trigger a refetch of the most up-to-date data from the backend. See urql's docs on re-executing queries for more information.

useEnqueue() 

useEnqueue(actionFunction: ModelActionFunction || GlobalActionFunction, actionInput, backgroundActionOptions = {}): [{error, fetching, handle}, enqueue]

useEnqueue facilitates the enqueuing of actions to be executed in the background.

web/components/CreateUserButton.jsx
JavaScript
1import { useEnqueue } from "react";
2import { api } from "../api";
3
4export function CreateUserButton(props: { name: string, email: string }) {
5 const [{ error, fetching, data, handle }, enqueue] = useEnqueue(api.user.create);
6
7 const onClick = () =>
8 enqueue(
9 {
10 // actionInput
11 name: props.name,
12 email: props.email,
13 },
14 {
15 // backgroundActionoptions
16 id: `send-email-action-${props.email}`,
17 }
18 );
19
20 return (
21 <>
22 {error && <>Failed to enqueue user create: {error.toString()}</>}
23 {fetching && <>Enqueuing action...</>}
24 {data && <>Enqueued action with background action id={handle.id}</>}
25 <button onClick={onClick}>Create user</button>
26 </>
27 );
28}
Parameters 
  • actionFunction: ModelActionFunction || GlobalActionFunction: Either a model or global action.
  • actionInput: Input | null: The parameters or data passed to a model or global action.
  • backgroundActionOptions (optional): The options for how the background action runs, for more information check out the reference here.
Returns 

useEnqueue doesn't submit the background action when invoked but instead returns a function for enqueuing the action in response to the event.

useActionForm() 

useActionForm(actionFunction: ModelActionFunction, options: UseActionFormOptions = {}): UseActionFormResult

useActionForm manages form state for calling actions in your Gadget backend. useActionForm can fetch the record for editing, manage the state of the fields as the user changes them in a form, track validations and errors, and then call the action with the form data when the user submits the form. useActionForm can call Actions on models as well as Global Actions.

useActionForm wraps the excellent react-hook-form library and provides all the same state management primitives that react-hook-form does, in addition to Gadget-specific goodies like automatic record fetching, automatic action calling and type safety.

JavaScript
1import { useActionForm } from "@gadgetinc/react";
2import { api } from "../api";
3
4const PostForm = () => {
5 const { register, submit } = useActionForm(api.post.create);
6
7 return (
8 <form onSubmit={submit}>
9 <label htmlFor="title">Title</label>
10 <input id="title" type="text" {...register("post.title")} />
11
12 <label htmlFor="content">Content</label>
13 <textarea id="content" {...register("post.content")} />
14 <input type="submit" />
15 </form>
16 );
17};

Read more about building forms in the Frontend Forms guide.

Parameters 
  • action: the Model Action or Global Action to call when submitting. Required.
  • options: the configuration for the form

The options options object accepts the following options:

NameTypeDescription
defaultValuesPartial<ActionInput>Default values to seed the form inputs with. Can be omitted. Mutually exclusive with the findBy. option.
findBystring or { [field: string]: any }Details for automatically finding a record to seed the form values with. When passed as a string, will look up a record with that id. When passed an object, will call a findBy<Field> function on the api object to retrieve a record by that field.
mode"onChange" or "onBlur" or "onSubmit" or "onTouched" or "all"Validation strategy before submitting behavior
reValidateMode"onChange" or "onBlur" or "onSubmit"Validation strategy after submitting behavior
resetOptionsResetOptionsDefault options to use when calling reset. For more details, see the reset function docs
criteriaMode"firstError" or "all"Display all validation errors or one at a time.
shouldFocusErrorbooleanEnable or disable built-in focus management.
delayErrornumberDelay errors by this many milliseconds to avoid them appearing instantly
shouldUseNativeValidationbooleanUse browser built-in form constraint API.
shouldUnregisterbooleanEnable and disable input unregister after unmount.
selectRecordSelectionWhich fields to select from the backend when retrieving initial data with findBy. See docs on the select option for more
sendstring[]Which fields to send from the form values to the backend for the action. Useful if you want to include fields in your form state for driving UI that shouldn't be sent with the submission
onSubmit() => voidCallback called right before data is submitted to the backend action
onSuccess(actionResult: ActionResultData) => voidCallback called after a successful submission to the backend action. Passed the action result, which is the object with {data, error, fetching} keys
onError(error: Error | FieldErrors) => voidCallback called after an error occurs finding the initial record or during submission to the backend action. Passed the error, which can be a transport error from a broken network, or a list of validation errors returned by the backend

useActionForm's props input is very similar to useForm's from react-hook-form. For more docs on these props, see the react-hook-form docs.

Returns 

useActionForm returns a variety of functions and state for managing your form that most users destructure as they call it:

JavaScript
const { register, submit, error, reset, ...rest } = useActionForm(api.post.update, {
defaultValues: { id: "123" },
});

The available result values are:

NameTypeDescription
registerFunctionA function for registering uncontrolled inputs with the form docs
unregisterFunctionA function for de-registering uncontrolled inputs with the form. Needed when dynamically adjusting the form elements on screen. docs
formStateFormStateCurrent state of the form, like validations, errors, submission details, etc docs
submit(event?: React.Event) => Promise<ActionResult>A function to call that submits the form to the backend. Returns a promise for the ActionResult object containing the {data, error, fetching} triple returned by the backend action.
watch(names?: string | string[] | (data, options) => void) => unknownA function for observing form values for easily changing how a form is displayed. docs
reset<T>(values?: T | ResetAction<T>, options?: Record<string, boolean>) => voidFunction for resetting the entire form state to specific values. docs
resetField(name: string, options?: Record<string, boolean | any>) => voidFunction for resetting one field in the values to a specific value. docs
setError(name: string, error: FieldError, { shouldFocus?: boolean }) => voidFunction for manually adding errors to fields. docs
clearErrors(name?: string | string[]) => voidFunction for removing all the errors or errors on one field. docs
setValue(name: string, value: unknown, config?: Object) => voidFunction for setting one field to a specific value. docs
setFocus(name: string, options: SetFocusOptions) => voidFunction for imperatively focusing one field. docs
getValues(payload?: string | string[]) => ObjectFunction for retrieving all the values from within the form state. docs
getFieldState(name: string, formState?: Object) => ({isDirty, isTouched, invalid, error})Function for returning the state of one individual field from within the form state. docs
trigger(name?: string | string[]) => Promise<boolean>Manually triggers form or input validation. This method is also useful when you have dependant validation (input validation depends on another input's value). docs
controlFormControlContext object for passing to <Controller/> components wrapping ref-less or controlled components
errorError | nullAny top-level Error objects encountered during processing. Will contain transport level errors as well as field validation errors returned by the backend. This value is for deeply inspecting the error if you want more than just the message, but the formState.errors object should be preferred if not.
actionData{data: Result | null, error: Error | null, fetching: false }The ActionResult triple returned by the inner useAction hook. Will be populated with the action execution result after submission.

FormState object 

The FormState object returned by useActionForm includes the following properties:

NameTypeDescription
isDirtybooleantrue if the user has modified any inputs away from the defaultValues, and false otherwise
dirtyFieldsRecord<string, boolean>A map of fields to the dirty state for each field. Each field's property on the object true if the user has modified this field away from the default and false otherwise
touchedFieldsRecord<string, boolean>A map of fields to the touched state for each field. Each field's property on the object true if the user has modified this field at all and false otherwise
defaultValuesRecord<string, any>The default values the form started out with, or has been reset to
isSubmittedbooleantrue if the form has ever been submitted, false otherwise
isSubmitSuccessfulbooleantrue if the form has completed a submission that encountered no errors, false otherwise
isSubmittingbooleantrue if the form is currently submitting to the backend, false otherwise
isLoadingbooleantrue if the form is currently loading data from the backend to populate the initial values or another input, false otherwise
submitCountnumberCount of times the form has been submitted
isValidbooleantrue if the form has no validation errors currently, false otherwise
isValidatingbooleantrue if the form is currently validating data, false otherwise
errorsRecord<string, string>A map of any validation errors currently present on each field

The FormState object managed by useActionForm (and react-hook-form underneath) is a Proxy object that tracks which properties are accessed during rendering to avoid excessive re-renders. Make sure you read its properties within a component render function to properly track which properties should trigger re-renders.

For more on this proxy object, see the react-hook-form docs

For more on the FormState object, see the react-hook-form docs.

Missing options from react-hook-form 

Unlike react-hook-form, useActionForm manages the submission process to your backend action. You don't need to manually make a call to your action -- instead, call the submit function returned by useActionForm when you are ready to submit the form, and useActionForm will call the action.

Because the submission process is managed, useActionForm does not accept the handleSubmit option that react-hook-form does.

<Controller/> 

useActionForm's register function only works with uncontrolled components that conform to normal DOM APIs. For working with controlled components, like those from popular UI libraries such as @shopify/polaris, you must register these input components with a <Controller/> instead.

JavaScript
1import { TextField } from "@shopify/polaris";
2import { useActionForm, Controller } from "@gadgetinc/react";
3import { api } from "../api";
4
5const AllowedTagForm = () => {
6 const { submit, control } = useActionForm(api.allowedTag.create);
7
8 return (
9 <form onSubmit={submit}>
10 <Controller
11 name="keyword"
12 control={control}
13 required
14 render={({ field }) => {
15 // Functional components like the Polaris TextField do not allow for 'ref's to be passed in
16 // Remove it from the props passed to the TextField
17 const { ref, ...fieldProps } = field;
18 // Pass the field props down to the textField to set the value value and add onChange handlers
19 return (
20 <TextField
21 label="Keyword"
22 type="text"
23 autoComplete="off"
24 {...fieldProps}
25 />
26 );
27 }}
28 />
29 </form>
30 );
31};

<Controller/> accepts the following props:

NameTypeDescription
namestring | FieldPathThe key of this input's data within your form's field values
controlFormControlContext object returned by useActionForm, must be passed to each <Controller/> to tie them to the form
render(props: ControllerProps) => ReactElementA function that returns a React element and provides the ability to attach events and value into the component. This simplifies integrating with external controlled components with non-standard prop names. Provides onChange, onBlur, name, ref and value as props for sending to the child component, and also a fieldState object which contains specific input state.
defaultValueunknownA default value for applying to the inner input.
rulesobjectValidation options for applying to the form value. Accepts the same format of options as the register function.
shouldUnregisterbooleanShould this input's values/validations/errors be removed on unmount.
disabledbooleanIs this input currently disabled such that it can't be edited

For more information on <Controller/>, see the react-hook-form docs

useFetch() 

useFetch(path: string, options: RequestInit = {})

useFetch is a low-level hook for making an HTTP request to your Gadget backend's HTTP routes. useFetch preserves client-side authentication information by using api.fetch under the hood, which means fetches will use the same request identity as other GraphQL API calls using the other hooks.

Gadget apps get an autogenerated API for reading and writing data to your models, which is often faster and easier to use than useFetch. See your app's API reference for more information.

JavaScript
1import { useFetch } from "@gadgetinc/react";
2
3export function UserByEmail(props) {
4 const [{ data, fetching, error }, refresh] = useFetch("/users/me", {
5 method: "GET",
6 headers: {
7 "content-type": "application/json",
8 },
9 json: true,
10 });
11
12 if (result.error) return <>Error: {result.error.toString()}</>;
13 if (result.fetching && !result.data) return <>Fetching...</>;
14 if (!result.data) return <>No user found with id={props.id}</>;
15
16 return <div>{result.data.name}</div>;
17}
Parameters 
  • path: the server-side URL to fetch from. Corresponds to an HTTP route defined on in your backend Gadget app's routes folder
  • options: options configuring the fetch call, corresponding exactly to those you might send with a normal fetch.
    • method: the request method, like "GET", "POST", etc. Defaults to "GET"
    • headers: the request headers, like { "content-type": "application/json" }
    • body: the request body to send to the server, like "hello" or JSON.stringify({foo: "bar"})
    • json: If true, expects the response to be returned as JSON, and parses it for convenience
    • stream:
      • If true, response will be a ReadableStream object, allowing you to work with the response as it arrives
      • If "string", will decode the response as a string and update data as the response arrives; this is useful when streaming responses from LLMs
    • onStreamComplete: a callback function that will be called with the final content when the streaming response is complete; this is only available when the stream: "string" option is set
    • sendImmediately: If true, sends the first fetch on component mount. If false, waits for the send function to be called to send a request. Defaults to true for GET requests and false for any other HTTP verbs.
    • See all the fetch options on MDN
Returns 

useFetch returns a tuple with the current state of the request and a function to send or re-send the request. The state is an object with the following fields:

  • data: the response data, if the request was successful
  • fetching: a boolean describing if the fetch request is currently in progress
  • streaming: a boolean describing if the fetch request is currently streaming. This is only set when the option { stream: "string" } is set
  • error: an error object if the request failed in any way

The second return value is a function for sending or resending the fetch request.

Request method 

By default, GET requests are sent as soon as the hook executes. GET requests can also be refreshed by calling the second return value to re-send the fetch request and fetch fresh data.

JavaScript
// GET request will be sent immediately, can be refreshed by calling `send()` again
const [{ data, fetching, error }, send] = useFetch("/some/route", { method: "GET" });
// ... sometime later
data; // => will be populated

Other request methods like POST, DELETE, etc will not be sent automatically. The request will only be sent when the send functions is called explicitly, often in a click handler or similar.

JavaScript
1// POST requests will not be sent until `send` is called explicitly
2const [{ data, fetching, error }, send] = useFetch("/some/route", {
3 method: "POST",
4 body: JSON.stringify({}),
5});
6// ... sometime later
7data; // => will still be undefined
8await send();
9data; // => will be populated

Sending request bodies 

useFetch supports sending data to the server in the request body using the body option. Bodies are only suppored for HTTP verbs which support them, like POST, PUT, PATCH, and DELETE.

To send a request body, pass a string, Buffer, or Stream object in the body key, and set the content-type header to match the type of data you are sending.

JavaScript
1const [{ data, fetching, error }, send] = useFetch("/some/path", {
2 method: "POST",
3 body: JSON.stringify({ foo: "bar" }),
4 headers: {
5 "content-type": "application/json",
6 },
7});

This will send your data to a backend routes/some/POST-path.js file, where request.body will be { foo: "bar" }.

Parsing the response 

Unlike the useFind hooks, useFetch doesn't automatically parse and return rich data from your HTTP route. By default, useFetch returns a string of the response for the data. But, there's a couple convenience options for quickly parsing the response into the shape you need.

Pass the { json: true } option to expect a JSON response from the server, and to automatically parse the response as JSON.

Pass the { stream: true } to get a ReadableStream object as a response from the server, allowing you to work with the response as it arrives. Otherwise, the response will be returned as a string object.

Pass the { stream: "string" } to decode the ReadableStream as a string and update data as it arrives. If the stream is in an encoding other than utf8 pass the encoding i.e. { stream: "utf-16" }. When { stream: "string" } is used, the streaming field in the state will be set to true while the stream is active, and false when the stream is complete. You can use this to show a loading indicator while the stream is active. You can also pass an onStreamComplete callback that will be called with the final string content when the stream is complete.

JavaScript
1const [{ data, fetching, streaming }, sendChat] = useFetch("/chat", {
2 method: "POST",
3 headers: {
4 "content-type": "application/json",
5 },
6 stream: "string",
7 // optional callback
8 // onStreamComplete: (content) => console.log(content)
9});

When to use useFetch vs useFindMany etc 

When possible, the hooks which make requests to your structured GraphQL API should be preferred. Your app's GraphQL API is autogenerated and full of useful features, which means you don't need to wire up custom routes on your backend to serve data. The API hooks provide built in type safety, error handling, caching, and useFetch does not.

Calling third-party APIs with useFetch 

@gadgetinc/react's useFetch hook calls fetch under the hood both client side and server side, which means you can use it to make HTTP requests to services other than your Gadget backend. You don't have to use useFetch to make calls elsewhere, but it is handy for avoiding adding other dependencies to your frontend code.

For example, we can call a third-party JSON API at dummyjson.com:

JavaScript
1export function DummyProducts(props) {
2 const [{ data, fetching, error }, resend] = useFetch(
3 "https://dummyjson.com/products",
4 {
5 method: "GET",
6 json: true,
7 }
8 );
9
10 if (result.error) return <>Error: {result.error.toString()}</>;
11 if (result.fetching && !result.data) return <>Fetching...</>;
12
13 return <div>{JSON.stringify(result.data.products)}</div>;
14}

useFetch will not send your Gadget API client's authentication headers to third party APIs. It will behave like a normal browser fetch call, just with the added React wrapper and json: true option for easy JSON parsing.

When the request gets sent 

By default, useFetch will immediately issue HTTP requests for GETs when run. This makes it easy to use useFetch to retrieve data for use rendering your component right away.

JavaScript
export function GetRequest(props) {
// will automatically send the request when the component renders the first time, as it is a GET
const [{ data, fetching, error }, resend] = useFetch("/products");
// fetching will be `true`
}

useFetch will not immediately issue HTTP requests for HTTP verbs other than GET, like POST, PUT, etc. The HTTP request will only be sent when you call the returned send function.

JavaScript
1export function PostRequest(props) {
2 // will not automatically send the request when the component renders, call `send` to issue the request
3 const [{ data, fetching, error }, send] = useFetch("/products", {
4 method: "POST",
5 });
6 // fetching will be `false`
7}

This behavior can be overridden with the sendImmediately option. You can avoid sending GET requests on render by passing sendImmediately: false:

JavaScript
1export function DelayedGetRequest(props) {
2 // will not automatically send the request when the component renders, call `send` to issue the request
3 const [{ data, fetching, error }, send] = useFetch("/products", {
4 sendImmediately: false,
5 });
6 // fetching will be `false`
7}

You can also have POST or PUT requests immediately issued by passing sendImmediately: true:

JavaScript
1export function ImmediatePutRequest(props) {
2 // will automatically send the request when the component renders the first time
3 const [{ data, fetching, error }, send] = useFetch("/products", {
4 method: "POST",
5 sendImmediately: true,
6 });
7 // fetching will be `true`
8}

useSession() 

Returns the current session for the user viewing the app.

jsx
1import { useSession } from "@gadgetinc/react";
2import { Client } from "@gadget-client/my-app";
3
4const api = new Client();
5
6const WhoAmI = () => {
7 const session = useSession(api);
8
9 return <>{session ? `You are signed in with session id ${session.id} as ${session.user.email}` : "You are not signed in"}</>;
10};

useSession will suspend your application if session data hasn't been loaded yet. See React's Suspense docs for more information.

useUser() 

Returns the current user of the session, if present. For unauthenticated sessions, returns null.

jsx
1import { useUser } from "@gadgetinc/react";
2import { Client } from "@gadget-client/my-app";
3
4const api = new Client();
5
6const WhoAmI = () => {
7 const user = useUser(api);
8
9 return <>{user ? `You are signed in as ${user.email}` : "You are not signed in"}</>;
10};

useUser will suspend your application if session data hasn't been loaded yet. See React's Suspense docs for more information.

useAuth() 

Returns an object representing the current authentication state of the session.

tsx
1import { useUser } from "@gadgetinc/react";
2import { Client } from "@gadget-client/my-app";
3
4const api = new Client();
5
6function App() {
7 const user = useUser(api);
8 const { isSignedIn } = useAuth(api);
9 const gadgetContext = useGadgetContext();
10
11 return (
12 <>
13 {isSignedIn ? <p>Hello, {user.firstName} {user.lastName}}</p> : <a href={gadgetContext.auth.signInPath}>Please sign in</a> }
14 </>
15 );
16}
Returns 
  • user - the current User, if signed in. Similar to useUser.
  • session - the current Session. Similar to useSession.
  • isSignedIn - set to true if the session has a user associated with it (signed in), false otherwise.

The select option 

The select option allows you to choose which fields and subfields are returned by your Gadget app's GraphQL API. Your app's API supports returning only some fields of each model you request, as well as fields of related models through the Gadget relationship field types. The select option is an object with keys representing the apiIdentifier of fields in your Gadget models, and values holding a boolean describing if that field should be selected or not, or a subselection for object-typed fields.

For example, you can limit the fields selected by a finder to only return some fields, lowering the amount of bandwidth used and making your requests faster:

JavaScript
1export const OnlySomeWidgetFields = (props: { id: string }) => {
2 // fetch only the widget id and name fields
3 const [{ data, fetching, error }, _refetch] = useFindOne(api.widget, props.id, {
4 select: { id: true, name: true },
5 });
6
7 return (
8 <span className="widget-name">
9 {data?.id}: {data?.name}
10 </span>
11 );
12};

You can also use the select option for selecting fields of related models. For example, if we have a backend Blog Post model which has a HasMany field to a Comment model, we can fetch a blog post and it's related comments:

JavaScript
1export const BlogWithComments = (props: { id: string }) => {
2 // fetch only the blogPost id and name fields ...
3 const [{ data, fetching, error }, _refetch] = useFindOne(api.blogPost, props.id, {
4 select: {
5 id: true,
6 title: true,
7 body: true,
8 // and fetch the post's `comments` HasMany relationship field on the post
9 comments: {
10 edges: {
11 node: {
12 id: true,
13 body: true,
14 // and fetch the author's BelongsTo User relationship field also
15 author: {
16 email: true,
17 },
18 },
19 },
20 },
21 },
22 });
23
24 if (!data) return null;
25 return (
26 <>
27 <h2>{data.title}</h2>
28 <ul>
29 {data.comments.edges.map((edge) => (
30 <li>
31 {edge.node.author.email} says {edge.node.body}
32 </li>
33 ))}
34 </ul>
35 </>
36 );
37};

Note: The shape of the options you pass in the select option matches exactly the shape of the GraphQL API for your application. Gadget applications use Relay-style GraphQL pagination, which means lists of records are accessed using the relatedField: { edges: { node: true } } style. BelongsTo and HasOne field types are accessed without any intermediate fields.

For TypeScript users, the select option is fully typesafe, allowing you to typecheck which fields you're fetching from the backend as well as ensure that the fields you render in your components are actually selected.

The live option 

The live option makes your component re-render when the data it is showing changes for any reason in the database. Passing live: true sets up a special @live query from your frontend to the Gadget backend which subscribes to changes in the on-screen data, and will continue streaming in those changes as they happen while the component remains mounted.

For example, we can show users a live view of the list of widgets from the backend with useFindMany(api.widget, { live: true }):

JavaScript
1export const LiveWidgets = () => {
2 const [{ data, fetching, error }] = useFindOne(api.widget, { live: true });
3
4 // will re-render when widgets change
5 return (
6 <span className="widget-name">
7 {data?.id}: {data?.name}
8 </span>
9 );
10};

live: true can be combined with the other options you might pass hooks, like the select option for selecting fields of related models, or the filter and sort opions for limiting the result set. Hooks passed live: true will respect the given selection, filtering, sorting, and pagination, and only trigger re-renders when the relevant backend data changes.

JavaScript
1export const BlogWithComments = (props: { id: string }) => {
2 const [{ data, fetching, error }, _refetch] = useFindOne(api.blogPost, props.id, {
3 live: true,
4 select: {
5 id: true,
6 title: true,
7 body: true,
8 // fetch the post's `comments` HasMany relationship field on the post
9 comments: {
10 edges: {
11 node: {
12 id: true,
13 body: true,
14 // fetch the author's BelongsTo User relationship field also
15 author: {
16 email: true,
17 },
18 },
19 },
20 },
21 },
22 });
23
24 if (!data) return null;
25 // will re-render when the blog post changes, any of its comments change, or any of the comment authors' emails change
26 return (
27 <>
28 <h2>{data.title}</h2>
29 <ul>
30 {data.comments.edges.map((edge) => (
31 <li>
32 {edge.node.author.email} says {edge.node.body}
33 </li>
34 ))}
35 </ul>
36 </>
37 );
38};

Live query result values 

When using live: true, your hook will the same thing the non-live variants do, which is a tuple with:

  • a data object containing the up-to-date result from the backend
  • a fetching boolean describing if the initial data fetch has completed or not
  • an error object describing any errors encountered during execution at any point

When the live: true hook mounts, it will fetch some initial data, then keep it up to data over time by subscribing to the backend. The fetching boolean describes if the initial data fetch has happened. Once the initial fetch is complete, the fetching boolean will be false, and new data will appear in the data object.

Errors from the returned error object 

Running queries or mutations can produce a few different kinds of errors your client side should handle:

  • network errors where the browser is unable to connect to the server at all
  • validation errors where the client sent information to the server successfully, but the server deemed it invalid and rejected it
  • server side errors where the client sent information to the server but the server failed to process it due to a bug or transient issue.

Each of these error cases is broken out on the error object returned by useAction (and any of the other hooks). The error object is an ErrorWrapper object, which has a number of properties for figuring out exactly what went wrong:

  • error.message: string - A top level error message which is always present
  • error.networkError: Error | undefined - An error thrown by the browser when trying to communicate with the server
  • error.executionErrors: (GraphQLError | GadgetError)[] | undefined - Any errors thrown by the GraphQL API, like missing parameters or invalid selections, and any errors thrown by the server concerning invalid data or backend processing errors.
  • error.validationErrors: { apiIdentifier: string, message: string }[] | undefined - Any validation errors returned by the server. A shortcut to accessing the .validationErrors property of the first InvalidRecordError in the .executionErrors of the outer ErrorWrapper object. Useful for building form validations.

Default selections 

Gadget makes a default selection when you don't pass the select option to a finder, which will include all the model's scalar fields and a small representation of its related records. This default is also type safe, so you can rely on the returned objects from default finder methods returning type safe results conforming to the default shape. To figure out exactly what your client will select by default for a model, see the documentation for that model in your generated API documentation.

The refetch function 

The refetch function returned as the second return value for some hooks can be executed in order to trigger a refetch of the most up to date data from the backend. This is useful for powering refresh buttons in user-facing UI, or for periodically updating the client side data. See urql's docs on re-executing queries for more information.

As an example, we could use the refetch function to power a refresh button in a table:

JavaScript
1import React from "react";
2import { api } from "../api";
3
4export const ShowWidgetNames = () => {
5 // get the second return value of `useFindMany`, which is the refetch function
6 const [{ data, fetching, error }, refetch] = useFindMany(api.widget);
7
8 if (fetching) return "Loading...";
9 if (error) return `Error loading data: ${error}`;
10
11 return (
12 <table>
13 <tr>
14 <th>ID</th>
15 <th>Name</th>
16 </tr>
17 {data.map((widget) => (
18 <tr key={widget.id}>
19 <td>{widget.id}</td>
20 <td>{widget.name}</td>
21 </tr>
22 ))}
23 <tr colspan="2">
24 <button onClick={() => void refetch()}>Refresh</button>
25 </tr>
26 </table>
27 );
28};

Suspense 

@gadgetinc/react supports two modes for managing loading states: the fetching return value, which will be true when making requests under the hood, as well as using <Suspense/>, React's next generation tool for managing asynchrony. Read more about <Suspense/> in the React docs.

To suspend rendering when fetching data, pass the suspense: true option to the useFind* hooks.

JavaScript
1const Posts = () => {
2 // pass suspense: true, and the component will only render once data has been returned
3 const [{ data, error }, refresh] = useFindMany(api.post, { suspense: true });
4
5 // note: no need to inspect the fetching prop
6 return (
7 <>
8 {data
9 .map
10 //...
11 ()}
12 </>
13 );
14};

All the read hooks support suspense: useFindOne, useMaybeFindOne, useFindMany, useFindFirst, useMaybeFindFirst, and useGet.

suspense: true is most useful when a parent component wraps a suspending-child with the <Suspense/> component for rendering a fallback UI while the child component is suspended:

JavaScript
<Suspense fallback={"loading..."}>
<Posts />
</Suspense>;

With this wrapper in place, the fallback prop will be rendered while the data is being fetched, and once it's available, the <Posts/> component will render with data.

Read more about <Suspense/> in the React docs. suspense: true uses urql's suspense support under the hood.

Request caching 

Under the hood, your Gadget app's API client and @gadgetinc/react use a powerful, production-grade GraphQL client called urql. urql has a great client-side data caching feature built-in called Document Caching which allows React components issuing GraphQL requests for the same data to de-duplicate requests and share client-side state. @gadgetinc/react enables this functionality by default.

@gadgetinc/react runs urql's Document Caching with a default requestPolicy of cache-and-network, which means your React hooks will re-render data with any cached results from the in-memory store, and then make an underlying HTTP request to fetch the most up to date data.

If you want to change the default requestPolicy that your Gadget API client and React hooks use, you can pass the requestPolicy option to your API client constructor.

JavaScript
// instantiate the API client for our app that will make network calls for every query, regardless of cache state
const api = new Client({
requestPolicy: "network-only",
});

There are four different request policies that you can use:

  • cache-first prefers cached results and falls back to sending an API request when no prior result is cached.
  • cache-and-network (the default) returns cached results but also always sends an API request, which is perfect for displaying data quickly while keeping it up-to-date.
  • network-only will always send an API request and will ignore cached results.
  • cache-only will always return cached results or null.

For more information on urql's built-in client-side caching, see urql's docs.

urql exports 

Since this library uses urql behind the scenes, it provides a few useful exports directly from urql so that it does not need to be installed as a peer dependency should you need to write custom queries or mutations.

The following are exported from urql:

  • Provider
  • Consumer
  • Context
  • useQuery
  • useMutation

Example usage:

JavaScript
1import React from "react";
2import { api } from "../api";
3import { Provider, useQuery } from "@gadgetinc/react";
4
5export const ShowWidgetNames = () => {
6 // find all widgets and the most recently created gizmo related to the widget
7 const [{ data, fetching, error }, refetch] = useQuery({
8 query: `
9query GetWidgets {
10 widgets {
11 edges {
12 node {
13 id
14 name
15 gizmos(first: 1, sort:{ createdAt: Descending }) {
16 edges {
17 node {
18 createdAt
19 }
20 }
21 }
22 }
23 }
24 }
25}
26 `,
27 });
28
29 if (fetching) return "Loading...";
30 if (error) return `Error loading data: ${error}`;
31
32 return (
33 <table>
34 <tr>
35 <th>ID</th>
36 <th>Name</th>
37 <th>Last Gizmo Created</th>
38 </tr>
39 {data.widgets.edges.map(({ node: widget }) => (
40 <tr key={widget.id}>
41 <td>{widget.id}</td>
42 <td>{widget.name}</td>
43 <td>
44 {widget.gizmos.edges.length > 0
45 ? widget.gizmos.edges[0].node.createdAt
46 : "Does not have Gizmos"}
47 </td>
48 </tr>
49 ))}
50 <tr colspan="2">
51 <button onClick={() => void refetch()}>Refresh</button>
52 </tr>
53 </table>
54 );
55};
56
57export const App = () => (
58 <Provider api={api}>
59 <ShowWidgetNames />
60 </Provider>
61);

Components 

If you are trying to control the layout of your application based on authentication state, it may be helpful to use the Gadget auth React components instead of, or in addition to, the hooks.

<SignedIn /> 

Conditionally renders its children if the current session has a user associated with it, similar to the isSignedIn property of the useAuth() hook.

tsx
<h1>
Hello<SignedIn>, human</SignedIn>!
</h1>

<SignedOut /> 

Conditionally renders its children if the current session does not have a user associated with it.

tsx
<SignedOut>
<a href="/auth/signin">Sign In!</a>
</SignedOut>

<SignedInOrRedirect /> 

Conditionally renders its children if the current session has a user associated with it, or redirects the browser via window.location.assign if the user is not currently signed in. This component is helpful for protecting front-end routes.

tsx
1<BrowserRouter>
2 <Routes>
3 <Route path="/" element={<Layout />}>
4 <Route index element={<Home />} />
5 <Route
6 path="my-profile"
7 element={
8 <SignedInOrRedirect>
9 <MyProfile />
10 </SignedInOrRedirect>
11 }
12 />
13 </Route>
14 </Routes>
15</BrowserRouter>

<SignedOutOrRedirect /> 

Conditionally renders its children if the current Session is signed out, otherwise redirects the browser to the path prop. Uses window.location.assign to perform the redirect.

tsx
1<BrowserRouter>
2 <Routes>
3 <Route path="/" element={<Layout />}>
4 <Route index element={
5 <SignedOutOrRedirect path="/my-profile">
6 <Home />
7 </SignedOutOrRedirect>
8 }>
9 <Route path="my-profile" element={<MyProfile />}
10 />
11 </Route>
12 </Routes>
13</BrowserRouter>

Authentication 

When working with Gadget auth, there are several hooks and components that can help you manage the authentication state of your application.

The Provider component exported from this library accepts an auth prop which can be used to configure the relative paths to your app's sign in and sign out endpoints. If you do not provide these paths, the default values of / and /signed-in will be used.

The hooks use the Gadget client's suspense: true option, making it easier to manage the async nature of the hooks without having to deal with loading state.

tsx
1import { Client } from "@gadget-client/my-gadget-app";
2import { Provider } from "@gadgetinc/react";
3import { Suspense } from "react";
4import App from "./App";
5
6// instantiate the API client for our app
7const api = new Client({ authenticationMode: { browserSession: true } });
8
9export function main() {
10 // ensure any components which use the @gadgetinc/react hooks are wrapped with the Provider and a Suspense component
11 return (
12 <Provider api={api} auth={{ signInPath: "/", signOutPath: "/signed-in" }}>
13 <Suspense fallback={<>Loading...</>}>
14 <App />
15 </Suspense>
16 </Provider>
17 );
18}