Task 

This page documents the task model.

Data Shape 

Gadget's database stores task records by storing and retrieving each of the fields defined on the model in the Gadget Editor to a managed database. Gadget has generated a GraphQL type matching the configured fields for task:

task Schema
1export type Task = {
2
3 __typename: 'Task';
4
5 /** The globally unique, unchanging identifier for this record. Assigned and managed by Gadget. */
6 id: string;
7
8 /** The time at which this record was first created. Set once upon record creation and never changed. Managed by Gadget. */
9 createdAt: Date;
10
11 /** The time at which this record was last changed. Set each time the record is successfully acted upon by an action. Managed by Gadget. */
12 updatedAt: Date;
13
14 /** The current state this record is in. Changed by invoking actions. Managed by Gadget. */
15 state: (string | { [key: string]: Scalars['RecordState'] });
16
17 description: (RichText | null);
18
19 owner: (User | null);
20
21 ownerId: string;
22
23 title: string;
24
25 /** Get all the fields for this record. Useful for not having to list out all the fields you want to retrieve, but slower. */
26 _all: Record<string, any>;
27};
1type Task {
2 """
3 The globally unique, unchanging identifier for this record. Assigned and managed by Gadget.
4 """
5 id: GadgetID!
6
7 """
8 The time at which this record was first created. Set once upon record creation and never changed. Managed by Gadget.
9 """
10 createdAt: DateTime!
11
12 """
13 The time at which this record was last changed. Set each time the record is successfully acted upon by an action. Managed by Gadget.
14 """
15 updatedAt: DateTime!
16
17 """
18 The current state this record is in. Changed by invoking actions. Managed by Gadget.
19 """
20 state: RecordState!
21 description: RichText
22 owner: User
23 ownerId: GadgetID
24 title: String!
25
26 """
27 Get all the fields for this record. Useful for not having to list out all the fields you want to retrieve, but slower.
28 """
29 _all: JSONObject!
30}

You can preview what a real record's shape looks like by fetching it using the  example-app API playground.

Any fetched task record will have this same Task type, and expose the same data by default, regardless of if it's fetched by ID or as part of a findMany. This means you can select any of the record's fields wherever you like in a GraphQL query according to the use case at hand.

Retrieving one task record 

Individual task records can be retrieved using the "find by ID" API endpoint. You can also return only some fields, or extra fields beyond what Gadget retrieves by default, using the select option.

The findOne function throws an error if no matching record is found, which you will need to catch and handle. Alternatively, you can use the maybeFindOne function, which returns null if no record is found, without throwing an error.

Similarly, the useFindOne React hook returns (but does not throw) an error when no matching record is found, while the useMaybeFindOne hook simply returns null if no record is found, without also returning an error.

Get one task
const taskRecord = await api.task.findOne("123");
// => a string
console.log(taskRecord.id);
// => a Date object
console.log(taskRecord.createdAt);
1const FindOneComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindOne(api.task, "123");
3
4// => a string
5console.log(data?.id);
6// => a Date object
7console.log(data?.createdAt);
8
9return <>{JSON.stringify(data)}</>;
10};
1query GetOneTask($id: GadgetID!) {
2 task(id: $id) {
3 __typename
4 id
5 state
6
7 # ...
8
9 createdAt
10 description {
11 markdown
12 truncatedHTML
13 }
14 ownerId
15 title
16 updatedAt
17 }
18}
Variables
json
{ "id": "123" }
const taskRecord = await api.task.findOne("123");
// => a string
console.log(taskRecord.id);
// => a Date object
console.log(taskRecord.createdAt);
1const FindOneComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindOne(api.task, "123");
3
4// => a string
5console.log(data?.id);
6// => a Date object
7console.log(data?.createdAt);
8
9return <>{JSON.stringify(data)}</>;
10};

Retrieving the first of many task records 

The first record from a list of records can be retrieved using the "find first" API endpoint. The source list of records can be filtered using the filter option, sorted using the sort option, searched using the search option, though no pagination options are available on this endpoint. You can also return only some fields, or extra fields beyond what Gadget retrieves by default using the select option.

The findFirst function throws an error if no matching record is found, which you will need to catch and handle. Alternatively, you can use the maybeFindFirst function, which returns null if no record is found, without throwing an error.

Similarly, the useFindFirst React hook returns (but does not throw) an error when no matching record is found, while the useMaybeFindFirst hook simply returns null if no record is found, without also returning an error.

Get first task
const taskRecord = await api.task.findFirst();
console.log(taskRecord.id); //=> a string
console.log(taskRecord.createdAt); //=> a Date object
1const FindFirstComponent = (props) => {
2 const [{data, error, fetching}, refresh] = useFindFirst(api.task);
3
4// => a string
5console.log(data?.id)
6// => a Date object
7console.log(data?.createdAt)
8
9return <>{JSON.stringify(data)}</>;
10};
1query FindManyTasks(
2 $first: Int
3 $search: String
4 $sort: [TaskSort!]
5 $filter: [TaskFilter!]
6) {
7 tasks(first: $first, search: $search, sort: $sort, filter: $filter) {
8 edges {
9 node {
10 __typename
11 id
12 state
13
14 # ...
15
16 createdAt
17 description {
18 markdown
19 truncatedHTML
20 }
21 ownerId
22 title
23 updatedAt
24 }
25 }
26 }
27}
Variables
json
{ "first": 1 }
const taskRecord = await api.task.findFirst();
console.log(taskRecord.id); //=> a string
console.log(taskRecord.createdAt); //=> a Date object
1const FindFirstComponent = (props) => {
2 const [{data, error, fetching}, refresh] = useFindFirst(api.task);
3
4// => a string
5console.log(data?.id)
6// => a Date object
7console.log(data?.createdAt)
8
9return <>{JSON.stringify(data)}</>;
10};

Retrieving many task records 

Pages of task records can be retrieved by using the "find many" API endpoint. The returned records can be filtered using the filter option, sorted using the sort option, searched using the search option, and paginated using standard Relay-style pagination options. You can also return only some fields, or extra fields beyond what Gadget retrieves by default using the select option.

This GraphQL endpoint returns records in the Relay Connection style (as a list of edges with nodes and cursors) so they can be paginated. The tasks GraphQL endpoint works with any Relay-compatible caching client, or you can use Gadget's JS client for pagination with the findMany function.

Find a page of tasks 

You can fetch one page of records with the task.findMany JS method or the tasks GraphQL field. No options are required, and records can be sorted with the sort option and filtered with the filter optional. The records returned will be implicitly sorted by ID ascending, unless you pass a sort option.

Find many tasks
const taskRecords = await api.task.findMany();
// => a number
console.log(taskRecords.length);
// => a string
console.log(taskRecords[0].id);
1const FindManyComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindMany(api.task);
3if (!data) return null;
4
5// => a number
6console.log(data.length)
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12};
1query FindManyTasks(
2 $after: String
3 $before: String
4 $first: Int
5 $last: Int
6 $search: String
7 $sort: [TaskSort!]
8 $filter: [TaskFilter!]
9) {
10 tasks(
11 after: $after
12 before: $before
13 first: $first
14 last: $last
15 search: $search
16 sort: $sort
17 filter: $filter
18 ) {
19 edges {
20 node {
21 __typename
22 id
23 state
24
25 # ...
26
27 createdAt
28 updatedAt
29 }
30 }
31 }
32}
Variables
json
{}
const taskRecords = await api.task.findMany();
// => a number
console.log(taskRecords.length);
// => a string
console.log(taskRecords[0].id);
1const FindManyComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindMany(api.task);
3if (!data) return null;
4
5// => a number
6console.log(data.length)
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12};

Your app's API is built using GraphQL, which makes it easy to retrieve data from related records through fields like belongs to and has many.

To optimize the performance of your API, data from related records is not retrieved by default, but you can change what data is retrieved with the `select` option to API calls.

For example, you can fetch belongs to data from the record linked by the owner field using the select option:

Get related data from owner
1const taskRecord = await api.task.findFirst({
2 select: {
3 id: true,
4 owner: {
5 id: true,
6 createdAt: true,
7 },
8 },
9});
10// => the related record's id
11console.log(taskRecord.owner?.id);
1const FindRelatedComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindFirst(api.task, {
3 select: {
4 id: true,
5 owner: {
6 id: true,
7 createdAt: true
8 }
9 }
10 });
11 if (!data) return null;
12 // show the related record's id
13 return <>
14 {data.owner?.id}
15 </>
16};
1const taskRecord = await api.task.findFirst({
2 select: {
3 id: true,
4 owner: {
5 id: true,
6 createdAt: true,
7 },
8 },
9});
10// => the related record's id
11console.log(taskRecord.owner?.id);
1const FindRelatedComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindFirst(api.task, {
3 select: {
4 id: true,
5 owner: {
6 id: true,
7 createdAt: true
8 }
9 }
10 });
11 if (!data) return null;
12 // show the related record's id
13 return <>
14 {data.owner?.id}
15 </>
16};

When using an explicit select option, be sure to include any fields you need from all models in your query, including the parent model. The default selection no longer applies when you pass select.

Retrieving a single task record by a uniquely identifiable field 

After adding a unique validation to a field, you can retrieve a single record by using the finders generated below. If you would like to edit the fields returned or filtering, see the filtering section.

Retrieving a single task record by id 

Individual task records can be retrieved using the "find many" API endpoint pre-filtered by the field's id. Throws if stored data is not unique.

Find tasks
const taskRecord = await api.task.findById("some-value");
// => a string
console.log(taskRecord.id);
1const FindByComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindBy(api.task.findById, "some-value");
3 // => a string
4 console.log(data?.id);
5
6return <>{JSON.stringify(data)}</>;
7}
const taskRecord = await api.task.findById("some-value");
// => a string
console.log(taskRecord.id);
1const FindByComponent = () => {
2 const [{data, error, fetching}, refresh] = useFindBy(api.task.findById, "some-value");
3 // => a string
4 console.log(data?.id);
5
6return <>{JSON.stringify(data)}</>;
7}

Sorting 

Records can be sorted in the database to retrieve them in a certain order. Records are always implicitly sorted by ID ascending unless an explicit sort on the id field is defined. The GraphQL type TaskSort defines which fields can be sorted by.

Records can be sorted by multiple different fields and in multiple different directions by passing a list of TaskSort instead of just one.

Pass the sort option to the JS client, or the sort variable to a GraphQL query to sort the records returned.

Sort task by most recently created
const taskRecords = await api.task.findMany({ sort: { createdAt: "Descending" } });
const [result, refresh] = useFindMany(api.task, { sort: { createdAt: "Descending" } });
const { data, error, fetching } = result;
1query FindManyTasks($sort: [TaskSort!]) {
2 tasks(sort: $sort) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "sort": { "createdAt": "Descending" } }
const taskRecords = await api.task.findMany({ sort: { createdAt: "Descending" } });
const [result, refresh] = useFindMany(api.task, { sort: { createdAt: "Descending" } });
const { data, error, fetching } = result;

Sort by multiple fields by passing an array of { [field]: "Ascending" | "Descending" } objects.

Sort task by multiple fields
const taskRecords = await api.task.findMany({
sort: [{ id: "Descending" }, { createdAt: "Ascending" }],
});
1const [result, refresh] = useFindMany(api.task, {
2 sort: [
3 { id: "Descending" },
4 { createdAt: "Ascending" }
5 ]
6});
7const { data, error, fetching } = result;
1query FindManyTasks($sort: [TaskSort!]) {
2 tasks(sort: $sort) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "sort": [{ "id": "Descending" }, { "createdAt": "Ascending" }] }
const taskRecords = await api.task.findMany({
sort: [{ id: "Descending" }, { createdAt: "Ascending" }],
});
1const [result, refresh] = useFindMany(api.task, {
2 sort: [
3 { id: "Descending" },
4 { createdAt: "Ascending" }
5 ]
6});
7const { data, error, fetching } = result;

Available fields for sorting 

You can sort task records by the following fields:

FieldSort type
idAscending / Descending
titleAscending / Descending
stateAscending / Descending
descriptionAscending / Descending
createdAtAscending / Descending
updatedAtAscending / Descending

For example, you can sort by the id field:

Sort tasks by id descending
const taskRecords = await api.task.findMany({
sort: { id: "Descending" },
});
const [result, refresh] = useFindMany(api.task, {
sort: { id: 'Descending'}
})
const { data, error, fetching } = result;
1query FindManyTasks($sort: [TaskSort!]) {
2 tasks(sort: $sort) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "sort": { "id": "Descending" } }
const taskRecords = await api.task.findMany({
sort: { id: "Descending" },
});
const [result, refresh] = useFindMany(api.task, {
sort: { id: 'Descending'}
})
const { data, error, fetching } = result;

Read more about sorting in the Sorting and Filtering reference.

Searching 

task records can be searched using Gadget's built in full text search functionality. Gadget search is appropriate for powering autocompletes, searchable tables, or other experiences where humans are writing search queries. It's typo tolerant, synonym aware and supports simple search operators like ! to exclude search terms.

Search Tasks by passing the search parameter with a search query string.

Search isn't field specific in Gadget -- all String or RichText field types are searched with the built in search functionality.

Full text search Tasks
const taskRecords = await api.task.findMany({
search: "a specific phrase to search for",
});
const [result, refresh] = useFindMany(api.task, {
search: "a specific phrase to search for",
});
const { data, error, fetching } = result;
1query FindManyTasks($search: String) {
2 tasks(search: $search) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "search": "a specific phrase to search for" }
const taskRecords = await api.task.findMany({
search: "a specific phrase to search for",
});

Filtering 

task records can be filtered to return only the appropriate records. Records can be filtered on any field, including those managed by Gadget or fields added by developers. Filters can be combined with sorts, searches and paginated using cursor-based Relay pagination.

Filter Tasks by passing the filter parameter with a filter object. Filter objects are nestable boolean conditions expressed as JS objects capturing a key, an operator, and usually a value.

Find Tasks created in the last day
const yesterday = new Date(Date.now() - 86400000);
const taskRecords = await api.task.findMany({
filter: { createdAt: { greaterThan: yesterday } },
});
const yesterday = new Date(Date.now() - 86400000);
const [result, refresh] = useFindMany(api.task, {
filter: { createdAt: { greaterThan: yesterday }}
})
const { data, error, fetching } = result;
1query FindManyTasks($filter: [TaskFilter!]) {
2 tasks(filter: $filter) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "filter": { "createdAt": { "greaterThan": "2024-11-20T09:52:25.123Z" } } }
const yesterday = new Date(Date.now() - 86400000);
const taskRecords = await api.task.findMany({
filter: { createdAt: { greaterThan: yesterday } },
});
const yesterday = new Date(Date.now() - 86400000);
const [result, refresh] = useFindMany(api.task, {
filter: { createdAt: { greaterThan: yesterday }}
})
const { data, error, fetching } = result;

Available fields for filtering 

The GraphQL type TaskFilter defines which fields can be filtered on.

Field

Filter type

idIDFilter
titleStringFilter
ownerBelongsToFilter
stateRecordStateFilter
descriptionRichTextFilter
createdAtDateTimeFilter
updatedAtDateTimeFilter

For example, we can filter task records on the id field:

const taskRecords = await api.task.findMany({
filter: {
id: { isSet: true },
},
});
1const [result, refresh] = useFindMany(api.task, {
2 filter: {
3 id: {isSet: true}
4 }
5})
6const { data, error, fetching } = result;
1query FindManyTasks($filter: [TaskFilter!]) {
2 tasks(filter: $filter) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
{ "filter": { "id": { "isSet": true } } }
const taskRecords = await api.task.findMany({
filter: {
id: { isSet: true },
},
});
1const [result, refresh] = useFindMany(api.task, {
2 filter: {
3 id: {isSet: true}
4 }
5})
6const { data, error, fetching } = result;

Read more about the available filters in the Sorting and Filtering reference.

Combining filters 

Records can be filtered by multiple different fields simultaneously. If you want to combine filters using boolean logic, nest them under the AND, OR, or NOT keys of a parent filter. Filters can be nested deeply by passing multiple levels boolean condition filters.

You can also pass a list of filters to the filter parameter which will be implicitly ANDed with one another such that they all need to match for a record to be returned.

Tasks created this week or updated today
1const yesterday = new Date(Date.now() - 86400000);
2const oneWeekAgo = new Date(Date.now() - 604800000);
3const taskRecords = await api.task.findMany({
4 filter: {
5 OR: [
6 {
7 createdAt: { greaterThan: oneWeekAgo },
8 },
9 {
10 updatedAt: { greaterThan: yesterday },
11 },
12 ],
13 },
14});
1const yesterday = new Date(Date.now() - 86400000);
2const oneWeekAgo = new Date(Date.now() - 604800000);
3const [result, refresh] = useFindMany(api.task, {
4 filter: {
5 OR: [
6 {
7 createdAt: { greaterThan: oneWeekAgo },
8 },
9 {
10 updatedAt: { greaterThan: yesterday },
11 },
12 ]
13 }
14})
15const { data, error, fetching } = result;
1query FindManyTasks($filter: [TaskFilter!]) {
2 tasks(filter: $filter) {
3 edges {
4 node {
5 __typename
6 id
7 state
8
9 # ...
10
11 createdAt
12 updatedAt
13 }
14 }
15 }
16}
Variables
json
1{
2 "filter": {
3 "OR": [
4 { "createdAt": { "greaterThan": "2024-11-14T09:52:25.123Z" } },
5 { "updatedAt": { "greaterThan": "2024-11-20T09:52:25.123Z" } }
6 ]
7 }
8}
1const yesterday = new Date(Date.now() - 86400000);
2const oneWeekAgo = new Date(Date.now() - 604800000);
3const taskRecords = await api.task.findMany({
4 filter: {
5 OR: [
6 {
7 createdAt: { greaterThan: oneWeekAgo },
8 },
9 {
10 updatedAt: { greaterThan: yesterday },
11 },
12 ],
13 },
14});
1const yesterday = new Date(Date.now() - 86400000);
2const oneWeekAgo = new Date(Date.now() - 604800000);
3const [result, refresh] = useFindMany(api.task, {
4 filter: {
5 OR: [
6 {
7 createdAt: { greaterThan: oneWeekAgo },
8 },
9 {
10 updatedAt: { greaterThan: yesterday },
11 },
12 ]
13 }
14})
15const { data, error, fetching } = result;

Pagination 

All Gadget record lists, including the top level task finder as well as associations to task, are structured as GraphQL connections. GraphQL connections are the de facto standard for querying lists and support cursor-based forward and backward pagination. When querying via GraphQL, you must select the edges field and then the node field to get the task record. When querying using a Gadget API client, the GraphQL queries are generated for you and the records are unwrapped and returned as a GadgetRecordList ready for use.

task pagination supports the standard GraphQL connection pagination arguments: first + after, or last + before. Pagination is done using cursors, which you can retrieve from the edge.cursor field or the pageInfo.startCursor properties.

Get the first page of 25 tasks
const taskRecords = await api.task.findMany({ first: 25 });
// => no greater than 25
console.log(taskRecords.length);
1const FirstPage = () => {
2 const [{ data, error, fetching }, refresh] = useFindMany(api.task, {first: 25})
3 if (!data) return null;
4
5// => no greater than 25
6console.log(data.length);
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12}
1query FindManyTasks($first: Int, $after: String) {
2 tasks(first: $first, after: $after) {
3 pageInfo {
4 hasNextPage
5 hasPreviousPage
6 startCursor
7 endCursor
8 }
9 edges {
10 cursor
11 node {
12 __typename
13 id
14 state
15
16 # ...
17
18 createdAt
19 updatedAt
20 }
21 }
22 }
23}
Variables
json
{ "first": 25 }
const taskRecords = await api.task.findMany({ first: 25 });
// => no greater than 25
console.log(taskRecords.length);
1const FirstPage = () => {
2 const [{ data, error, fetching }, refresh] = useFindMany(api.task, {first: 25})
3 if (!data) return null;
4
5// => no greater than 25
6console.log(data.length);
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12}
Next 25 task records after cursor
const taskRecords = await api.task.findMany({ after: "example-cursor", first: 25 });
1const SecondPage = (props) => {
2 const [{ data, error, fetching }, refresh] = useFindMany(api.task, {after: "example-cursor", first: 25});
3 if (!data) return null;
4
5// => no greater than 25
6console.log(data.length);
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12}
1query FindManyTasks($first: Int, $after: String) {
2 tasks(first: $first, after: $after) {
3 pageInfo {
4 hasNextPage
5 hasPreviousPage
6 startCursor
7 endCursor
8 }
9 edges {
10 cursor
11 node {
12 __typename
13 id
14 state
15
16 # ...
17
18 createdAt
19 updatedAt
20 }
21 }
22 }
23}
Variables
json
{ "first": 25, "after": "abcdefg" }
const taskRecords = await api.task.findMany({ after: "example-cursor", first: 25 });
1const SecondPage = (props) => {
2 const [{ data, error, fetching }, refresh] = useFindMany(api.task, {after: "example-cursor", first: 25});
3 if (!data) return null;
4
5// => no greater than 25
6console.log(data.length);
7
8return <>
9{data.map(record => JSON.stringify(record))}
10
11 </>
12}

Pagination Limits 

Root-level record finders like tasks support a maximum page size of 250 records and a default page size of 50 records. The page size is controlled using the first or last GraphQL field arguments.

Related record finders that access lists of records through a has many or has many through field support a maximum page size of 100 records and a default page size of 50 records.

Get the next or previous page 

When using the generated JavaScript API client, including the api parameter in a Gadget code effect, the record lists returned from findMany calls can be paginated using the nextPage() or previousPage() option.

Both nextPage() and previousPage() will throw an error if the corresponding hasNextPage or hasPreviousPage is false.

JavaScript
1const taskRecords = await api.task.findMany();
2if (taskRecords.hasNextPage) {
3 const nextPage = await taskRecords.nextPage();
4}
5if (taskRecords.hasPreviousPage) {
6 const prevPage = await taskRecords.previousPage();
7}
1const taskRecords = await api.task.findMany();
2if (taskRecords.hasNextPage) {
3 const nextPage = await taskRecords.nextPage();
4}
5if (taskRecords.hasPreviousPage) {
6 const prevPage = await taskRecords.previousPage();
7}

When using React and paging through records, you can use cursors to get the previous or next pages of records. This is an example of a React component that pages forward and backward through 2 records at a time for task.

React
1// your Gadget project's API Client
2import { api } from "../api";
3import { useFindMany } from "@gadgetinc/react";
4import { useCallback, useState } from "react";
5
6export default function TestComponent() {
7 // the number of records per page
8 const NUM_ON_PAGE = 2;
9
10 const [cursor, setCursor] = useState({ first: NUM_ON_PAGE });
11 // using Gadget React hooks to fetch records of task
12 const [{ data, fetching, error }] = useFindMany(api.task, {
13 ...cursor,
14 });
15
16 const getNextPage = useCallback(() => {
17 // use first + after to page forwards
18 setCursor({ first: NUM_ON_PAGE, after: data.endCursor });
19 }, [data]);
20
21 const getPreviousPage = useCallback(() => {
22 // use last + before to page backwards
23 setCursor({ last: NUM_ON_PAGE, before: data.startCursor });
24 }, [data]);
25
26 return (
27 <div>
28 <button onClick={getPreviousPage} disabled={!data?.hasPreviousPage}>
29 Previous page
30 </button>
31 <button onClick={getNextPage} disabled={!data?.hasNextPage}>
32 Next page
33 </button>
34 {!fetching && data.map((d) => <div>{d.id}</div>)}
35 </div>
36 );
37}
1// your Gadget project's API Client
2import { api } from "../api";
3import { useFindMany } from "@gadgetinc/react";
4import { useCallback, useState } from "react";
5
6export default function TestComponent() {
7 // the number of records per page
8 const NUM_ON_PAGE = 2;
9
10 const [cursor, setCursor] = useState({ first: NUM_ON_PAGE });
11 // using Gadget React hooks to fetch records of task
12 const [{ data, fetching, error }] = useFindMany(api.task, {
13 ...cursor,
14 });
15
16 const getNextPage = useCallback(() => {
17 // use first + after to page forwards
18 setCursor({ first: NUM_ON_PAGE, after: data.endCursor });
19 }, [data]);
20
21 const getPreviousPage = useCallback(() => {
22 // use last + before to page backwards
23 setCursor({ last: NUM_ON_PAGE, before: data.startCursor });
24 }, [data]);
25
26 return (
27 <div>
28 <button onClick={getPreviousPage} disabled={!data?.hasPreviousPage}>
29 Previous page
30 </button>
31 <button onClick={getNextPage} disabled={!data?.hasNextPage}>
32 Next page
33 </button>
34 {!fetching && data.map((d) => <div>{d.id}</div>)}
35 </div>
36 );
37}

Get all records 

If you need to get all available data for task, you will need to paginate through all pages of data. If you have a large amount of data, this can take a long time. Make sure you need to collect all data at once before writing a pagination loop that reads all records! If you are querying records for display in a UI and cannot display all your records at once, we don't recommend fetching all the data beforehand - instead, use the cursor to read additional data when the user needs it.

If you need all data for analytics applications or to collect some statistics on your data, consider options like intermediate models and pre-defined data rollups.

If you have determined that you need all your data, you can fetch it using cursors and a loop. We also suggest using select so that you only grab fields that are needed, in addition to applying a filter, if possible. Using first with the maximum allowable value will also allow you to grab the maximum number of records you can at once.

Page through all records
JavaScript
1// use allRecords to store all records
2const allRecords = [];
3let records = await api.task.findMany({
4 first: 250,
5 select: {
6 id: true,
7 },
8 filter: {
9 // add filter conditions, if possible
10 },
11});
12
13allRecords.push(...records);
14
15// loop through additional pages to get all protected orders
16while (records.hasNextPage) {
17 // paginate
18 records = await records.nextPage();
19 allRecords.push(...records);
20}
1// use allRecords to store all records
2const allRecords = [];
3let records = await api.task.findMany({
4 first: 250,
5 select: {
6 id: true,
7 },
8 filter: {
9 // add filter conditions, if possible
10 },
11});
12
13allRecords.push(...records);
14
15// loop through additional pages to get all protected orders
16while (records.hasNextPage) {
17 // paginate
18 records = await records.nextPage();
19 allRecords.push(...records);
20}

Selecting fields, and fields of fields 

When using the JavaScript client, all of findOne, maybeFindOne, findMany, findFirst, maybeFindFirst, and various action functions, allow requesting specific fields of a task and its relationships. The select option controls which fields are selected in the generated GraphQL query sent to the Gadget API. Pass each field you want to select in an object, with true as the value for scalar fields, and a nested object of the same shape for nested fields.

Gadget has a default selection that will retrieve all of the scalar fields for a task. If you don't pass a select option to a record finder, this default selection will be used.

Select only some task fields
1// fetch only the id and createdAt field
2const taskRecords = await api.task.findMany({
3 select: { id: true, createdAt: true },
4});
5// fetch all the scalar fields for the model, but no relationship fields
6const taskRecords = await api.task.findMany();
const SelectionComponent = (props) => {
// fetch only the id and createdAt field
const [{data, error, fetching}, refresh] = useFindMany(api.task, {select: { id: true, createdAt: true }});
// ...
}
1// fetch only the id and createdAt field
2const taskRecords = await api.task.findMany({
3 select: { id: true, createdAt: true },
4});
5// fetch all the scalar fields for the model, but no relationship fields
6const taskRecords = await api.task.findMany();
const SelectionComponent = (props) => {
// fetch only the id and createdAt field
const [{data, error, fetching}, refresh] = useFindMany(api.task, {select: { id: true, createdAt: true }});
// ...
}

Realtime subscriptions with live queries 

Each read function in the task runs once and returns a static set of results. There is also a second mode for subscribing to the results of the query as they change over time.

By passing live: true to any read query or hook, you'll get a stream of results as data changes in the backend, instead of just one result. This is useful for automatically updating your UI when any record is created, updated, or deleted in your backend database.

Realtime queries are issued by passing live: true to your API call or React hook. For example, you can query and stream changes to the record with id 123:

Fetch task 123 in live mode
// calling findOne with live: true will return a stream of results as an AsyncIterator, not just one result
for await (const record of api.task.findOne("123", { live: true })) {
// record will be a GadgetRecord object
console.log("new record version", record);
}
1export const Record123 = (props) => {
2 const [{data, error, fetching}] = useFindOne(api.task,
3 "123", // the id of the record to fetch
4 {
5 // make this a realtime live query
6 live: true,
7 });
8 if (!data) return null;
9 return (
10 <div>
11 Record 123 last updated at {data.updatedAt}
12 </div>
13 );
14}
// calling findOne with live: true will return a stream of results as an AsyncIterator, not just one result
for await (const record of api.task.findOne("123", { live: true })) {
// record will be a GadgetRecord object
console.log("new record version", record);
}
1export const Record123 = (props) => {
2 const [{data, error, fetching}] = useFindOne(api.task,
3 "123", // the id of the record to fetch
4 {
5 // make this a realtime live query
6 live: true,
7 });
8 if (!data) return null;
9 return (
10 <div>
11 Record 123 last updated at {data.updatedAt}
12 </div>
13 );
14}

You can also subscribe to realtime results for pages of records. For example, we can fetch and render a list of the first ten task records, which will automatically update when backend data changes:

First 10 task records in live mode
// calling findMany with live: true will return a stream of results as an AsyncIterator, not just one result
for await (const list of api.task.findMany({ live: true, first: 10 })) {
// list will be an array of GadgetRecord objects
console.log("new query result", list);
}
1export const FirstPage = (props) => {
2 const [{data, error, fetching}] = useFindMany(api.task, {
3 // make this a realtime live query
4 live: true,
5 first: 10
6 });
7 if (!data) return null;
8 return (
9 <div>
10 {data.map((record) => (
11 <div key={record.id}>{record.id}</div>
12 ))}
13 </div>
14 );
15}
// calling findMany with live: true will return a stream of results as an AsyncIterator, not just one result
for await (const list of api.task.findMany({ live: true, first: 10 })) {
// list will be an array of GadgetRecord objects
console.log("new query result", list);
}
1export const FirstPage = (props) => {
2 const [{data, error, fetching}] = useFindMany(api.task, {
3 // make this a realtime live query
4 live: true,
5 first: 10
6 });
7 if (!data) return null;
8 return (
9 <div>
10 {data.map((record) => (
11 <div key={record.id}>{record.id}</div>
12 ))}
13 </div>
14 );
15}

For more information, see the Realtime Queries guide.

Type Safety 

The select option is fully type-safe if you're using TypeScript. The returned GadgetRecord type will have a <Shape> exactly matching the fields and nested fields you selected.

This behavior of selecting only some fields is built right into GraphQL. If you want to limit or expand what you retrieve from a GraphQL query, include or exclude those fields in your GraphQL query. For more information on executing GraphQL queries, see GraphQL.

Select nested task fields
1// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject`
2const taskRecords = await api.task.findMany({
3 select: {
4 id: true,
5 createdAt: true,
6 someRelatedObject: { id: true, createdAt: true },
7 },
8});
const SelectionComponent = (props) => {
// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject`
const [{data, error, fetching}, refresh] = useFindMany(api.task, {select: { id: true, createdAt: true, someRelatedObject: { id: true, createdAt: true } }});
// ...
}
1// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject`
2const taskRecords = await api.task.findMany({
3 select: {
4 id: true,
5 createdAt: true,
6 someRelatedObject: { id: true, createdAt: true },
7 },
8});
const SelectionComponent = (props) => {
// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject`
const [{data, error, fetching}, refresh] = useFindMany(api.task, {select: { id: true, createdAt: true, someRelatedObject: { id: true, createdAt: true } }});
// ...
}

Combining parameters 

Sort, search, filtering, selection, and pagination parameters can be combined to access the exact set of records needed for your use case.

Combining Parameters
1const taskRecords = await api.task.findMany({
2 search: "<some search query>",
3 sort: { createdAt: "Descending" },
4 filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000) } },
5 select: { id: true, createdAt: true },
6 first: 25,
7 after: "abcdefg",
8});
1const [result, refresh] = useFindMany(api.task, {
2 search: "<some search query>",
3 sort: { createdAt: "Descending" },
4 filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000)}},
5 select: { id: true, createdAt: true },
6 first: 25,
7 after: "abcdefg"
8});
9const { data, error, fetching } = result;
1query FindManyTasks(
2 $after: String
3 $before: String
4 $first: Int
5 $last: Int
6 $search: String
7 $sort: [TaskSort!]
8 $filter: [TaskFilter!]
9) {
10 tasks(
11 after: $after
12 before: $before
13 first: $first
14 last: $last
15 search: $search
16 sort: $sort
17 filter: $filter
18 ) {
19 edges {
20 node {
21 __typename
22 id
23 state
24
25 # ...
26
27 createdAt
28 description {
29 markdown
30 truncatedHTML
31 }
32 ownerId
33 title
34 updatedAt
35 }
36 }
37 }
38}
Variables
json
1{
2 "search": "<some search query>",
3 "sort": { "createdAt": "Descending" },
4 "filter": { "updatedAt": { "greaterThan": "2024-11-20T09:52:25.241Z" } },
5 "first": 25,
6 "after": "abcdefg"
7}
1const taskRecords = await api.task.findMany({
2 search: "<some search query>",
3 sort: { createdAt: "Descending" },
4 filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000) } },
5 select: { id: true, createdAt: true },
6 first: 25,
7 after: "abcdefg",
8});
1const [result, refresh] = useFindMany(api.task, {
2 search: "<some search query>",
3 sort: { createdAt: "Descending" },
4 filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000)}},
5 select: { id: true, createdAt: true },
6 first: 25,
7 after: "abcdefg"
8});
9const { data, error, fetching } = result;

Invoking Actions 

task records are changed by invoking Actions. Actions are the things that "do" stuff -- update records, make API calls, call backend code, etc. Actions with a GraphQL API trigger each have one corresponding GraphQL mutation and a corresponding function available in the API client libraries. Nested Actions can also be invoked with the API client, by providing the actions as input to any relationship fields.

Action Result format 

Each API action returns results in the same format that includes a success indicator, errors, and the actual result if the action succeeded. The result is the record that was acted on for a model action, or a list of records for a bulk action, or a JSON blob for Global Actions. Model actions that delete the record don't return the record.

The success field returns a boolean indicating if the action executed as expected. Any execution errors are returned in the errors object, which will always be null if success is true or contain ExecutionError objects if success is false.

ExecutionError objects always have a message describing what error prevented the action from succeeding, as well as a code attribute that gives a stable, searchable, human-readable error class code for referencing this specific error. Details on each error code can be found in the Errors documentation. All ExecutionError object types returned by the GraphQL object can be one of many types of error, where some types have extra data that is useful for remedying the error. All error types will always have message and code properties, but some, like InvalidRecordError have extra fields for use by clients.

Errors when using the generated client 

The generated JavaScript client automatically interprets errors from invoking actions and throws JavaScript Error instances if the action didn't succeed. The Error objects it throws are rich, and expose extra error properties beyond just message and code if they exist.

Errors thrown by the JavaScript client are easiest to catch by using a try/catch statement around an await, like so:

JavaScript
1import {
2 GadgetOperationError,
3 InvalidRecordError,
4} from "@gadgetinc/api-client-core";
5
6// must be in an async function to use await` syntax
7export async function run({ api }) {
8 try {
9 return await api.exampleModel.create({ name: "example record name" });
10 } catch (error) {
11 if (error instanceof GadgetOperationError) {
12 // a recognized general error has occurred, retry the operation or inspect \error.code\`
13 console.error(error);
14 } else if (error instanceof InvalidRecordError) {
15 // the submitted input data for the action was invalid, inspect the invalid fields which \`InvalidRecordError\` exposes
16 console.error(error.validationErrors);
17 } else {
18 // an unrecognized error occurred like an HTTP connection interrupted error or a syntax error. Re-throw it because it's not clear what to do to fix it
19 throw error;
20 }
21 }
22}
1import {
2 GadgetOperationError,
3 InvalidRecordError,
4} from "@gadgetinc/api-client-core";
5
6// must be in an async function to use await` syntax
7export async function run({ api }) {
8 try {
9 return await api.exampleModel.create({ name: "example record name" });
10 } catch (error) {
11 if (error instanceof GadgetOperationError) {
12 // a recognized general error has occurred, retry the operation or inspect \error.code\`
13 console.error(error);
14 } else if (error instanceof InvalidRecordError) {
15 // the submitted input data for the action was invalid, inspect the invalid fields which \`InvalidRecordError\` exposes
16 console.error(error.validationErrors);
17 } else {
18 // an unrecognized error occurred like an HTTP connection interrupted error or a syntax error. Re-throw it because it's not clear what to do to fix it
19 throw error;
20 }
21 }
22}

For more information on error codes, consult the Errors documentation.

task create 

Input 

create accepts the following input parameters:

create Input Data
1export type CreateTaskInput = {
2
3 description?: RichTextInput | null;
4
5 owner?: UserBelongsToInput | null;
6
7 title?: (Scalars['String'] | null) | null;
8};
9
10
11
12export type CreateTaskArguments = {
13
14 task?: CreateTaskInput | null;
15};
1input CreateTaskInput {
2 description: RichTextInput
3 owner: UserBelongsToInput
4 title: String
5}
6
7input CreateTaskArguments {
8 task: CreateTaskInput
9}
Example create Invocation
1const taskRecord = await api.task.create({
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 owner: {
6 _link: "123",
7 },
8 title: "example value for title",
9});
1const ExampleRunCreateComponent = (props) => {
2 const [{ data, error, fetching }, create] = useAction(api.task.create);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await create({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 owner: {
13 _link: "123",
14 },
15 title: "example value for title",
16 });
17 }}
18 >
19 Run Action
20 </button>
21 Result: {JSON.stringify(data)}
22 </>
23 );
24};
1mutation CreateTask($task: CreateTaskInput) {
2 createTask(task: $task) {
3 success
4 errors {
5 message
6 ... on InvalidRecordError {
7 validationErrors {
8 apiIdentifier
9 message
10 }
11 record
12 model {
13 apiIdentifier
14 }
15 }
16 }
17 task {
18 __typename
19 id
20 state
21 createdAt
22 description {
23 markdown
24 truncatedHTML
25 }
26 ownerId
27 title
28 updatedAt
29 }
30 }
31}
Variables
json
1{
2 "task": {
3 "description": { "markdown": "example _rich_ **text**" },
4 "owner": { "_link": "123" },
5 "title": "example value for title"
6 }
7}
1const taskRecord = await api.task.create({
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 owner: {
6 _link: "123",
7 },
8 title: "example value for title",
9});
1const ExampleRunCreateComponent = (props) => {
2 const [{ data, error, fetching }, create] = useAction(api.task.create);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await create({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 owner: {
13 _link: "123",
14 },
15 title: "example value for title",
16 });
17 }}
18 >
19 Run Action
20 </button>
21 Result: {JSON.stringify(data)}
22 </>
23 );
24};
Output 

create returns the task. In the JS client, the fields returned can be controlled with the select option. In GraphQL, the return format is the action result format, which includes the record if the action was successful. You can include or exclude the fields you need right in the mutation itself.

create Output Data
GraphQL
1type CreateTaskResult implements UpsertTaskResult {
2 success: Boolean!
3 errors: [ExecutionError!]
4 actionRun: String
5 task: Task
6}

task update 

Input 

update operates on one task in particular, identified by the id variable.update accepts the following input parameters:

update Input Data
1export type UpdateTaskInput = {
2
3 description?: RichTextInput | null;
4
5 owner?: UserBelongsToInput | null;
6
7 title?: (Scalars['String'] | null) | null;
8};
9
10
11
12export type UpdateTaskArguments = {
13
14 task?: UpdateTaskInput | null;
15};
1input UpdateTaskInput {
2 description: RichTextInput
3 owner: UserBelongsToInput
4 title: String
5}
6
7input UpdateTaskArguments {
8 task: UpdateTaskInput
9}
Example update Invocation
1const taskRecord = await api.task.update("123", {
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 owner: {
6 _link: "123",
7 },
8 title: "example value for title",
9});
1const ExampleRunUpdateComponent = (props) => {
2 const [{ data, error, fetching }, update] = useAction(api.task.update);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await update({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 id: "123",
13 owner: {
14 _link: "123",
15 },
16 title: "example value for title",
17 });
18 }}
19 >
20 Run Action
21 </button>
22 Result: {JSON.stringify(data)}
23 </>
24 );
25};
1mutation UpdateTask($task: UpdateTaskInput, $id: GadgetID!) {
2 updateTask(task: $task, id: $id) {
3 success
4 errors {
5 message
6 ... on InvalidRecordError {
7 validationErrors {
8 apiIdentifier
9 message
10 }
11 record
12 model {
13 apiIdentifier
14 }
15 }
16 }
17 task {
18 __typename
19 id
20 state
21 createdAt
22 description {
23 markdown
24 truncatedHTML
25 }
26 ownerId
27 title
28 updatedAt
29 }
30 }
31}
Variables
json
1{
2 "task": {
3 "description": { "markdown": "example _rich_ **text**" },
4 "owner": { "_link": "123" },
5 "title": "example value for title"
6 },
7 "id": "123"
8}
1const taskRecord = await api.task.update("123", {
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 owner: {
6 _link: "123",
7 },
8 title: "example value for title",
9});
1const ExampleRunUpdateComponent = (props) => {
2 const [{ data, error, fetching }, update] = useAction(api.task.update);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await update({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 id: "123",
13 owner: {
14 _link: "123",
15 },
16 title: "example value for title",
17 });
18 }}
19 >
20 Run Action
21 </button>
22 Result: {JSON.stringify(data)}
23 </>
24 );
25};
Output 

update returns the task. In the JS client, the fields returned can be controlled with the select option. In GraphQL, the return format is the action result format, which includes the record if the action was successful. You can include or exclude the fields you need right in the mutation itself.

update Output Data
GraphQL
1type UpdateTaskResult implements UpsertTaskResult {
2 success: Boolean!
3 errors: [ExecutionError!]
4 actionRun: String
5 task: Task
6}

task delete 

The delete action destroys the record.

Input 

delete operates on one task in particular, identified by the id variable.

Example delete Invocation
await api.task.delete("123");
1const ExampleRunDeleteComponent = (props) => {
2 const [{ data, error, fetching }, _delete] = useAction(api.task.delete);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await _delete({
9 id: "123",
10 });
11 }}
12 >
13 Run Action
14 </button>
15 Result: {JSON.stringify(data)}
16 </>
17 );
18};
1mutation DeleteTask($id: GadgetID!) {
2 deleteTask(id: $id) {
3 success
4 errors {
5 message
6 ... on InvalidRecordError {
7 validationErrors {
8 apiIdentifier
9 message
10 }
11 record
12 model {
13 apiIdentifier
14 }
15 }
16 }
17 }
18}
Variables
json
{ "id": "123" }
await api.task.delete("123");
1const ExampleRunDeleteComponent = (props) => {
2 const [{ data, error, fetching }, _delete] = useAction(api.task.delete);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await _delete({
9 id: "123",
10 });
11 }}
12 >
13 Run Action
14 </button>
15 Result: {JSON.stringify(data)}
16 </>
17 );
18};
Output 

delete deletes the record, so it returns void in the JS client. In GraphQL it returns only the success and errors from the action result format.

delete Output Data
GraphQL
type DeleteTaskResult {
success: Boolean!
errors: [ExecutionError!]
actionRun: String
}

task upsert 

Input 

upsert accepts the following input parameters:

upsert Input Data
1export type UpsertTaskInput = {
2
3 id?: (Scalars['GadgetID'] | null) | null;
4
5 description?: RichTextInput | null;
6
7 owner?: UserBelongsToInput | null;
8
9 title?: (Scalars['String'] | null) | null;
10};
11
12
13
14export type UpsertTaskArguments = {
15
16 /** An array of Strings */
17 on?: ((Scalars['String'] | null))[];
18
19 task?: UpsertTaskInput | null;
20};
1input UpsertTaskInput {
2 id: GadgetID
3 description: RichTextInput
4 owner: UserBelongsToInput
5 title: String
6}
7
8input UpsertTaskArguments {
9 """
10 An array of Strings
11 """
12 on: [String!]
13 task: UpsertTaskInput
14}
Example upsert Invocation
1const result = await api.task.upsert({
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 id: "123",
6 owner: {
7 _link: "123",
8 },
9 title: "example value for title",
10});
1const ExampleRunUpsertComponent = (props) => {
2 const [{ data, error, fetching }, upsert] = useAction(api.task.upsert);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await upsert({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 id: "123",
13 owner: {
14 _link: "123",
15 },
16 title: "example value for title",
17 });
18 }}
19 >
20 Run Action
21 </button>
22 Result: {JSON.stringify(data)}
23 </>
24 );
25};
1mutation UpsertTask($on: [String!], $task: UpsertTaskInput) {
2 upsertTask(on: $on, task: $task) {
3 success
4 errors {
5 message
6 }
7 }
8}
Variables
json
1{
2 "task": {
3 "description": { "markdown": "example _rich_ **text**" },
4 "id": "123",
5 "owner": { "_link": "123" },
6 "title": "example value for title"
7 }
8}
1const result = await api.task.upsert({
2 description: {
3 markdown: "example _rich_ **text**",
4 },
5 id: "123",
6 owner: {
7 _link: "123",
8 },
9 title: "example value for title",
10});
1const ExampleRunUpsertComponent = (props) => {
2 const [{ data, error, fetching }, upsert] = useAction(api.task.upsert);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await upsert({
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 id: "123",
13 owner: {
14 _link: "123",
15 },
16 title: "example value for title",
17 });
18 }}
19 >
20 Run Action
21 </button>
22 Result: {JSON.stringify(data)}
23 </>
24 );
25};
Output 

upsert returns the task. In the JS client, the fields returned can be controlled with the select option. In GraphQL, the return format is the action result format, which includes the record if the action was successful. You can include or exclude the fields you need right in the mutation itself.

upsert Output Data
GraphQL
interface UpsertTaskResult {
success: Boolean!
errors: [ExecutionError!]
actionRun: String
}

When running actions on the task model, you can set the value of any belongs to or has many relationships in the same API call.

Linking to an existing parent record 

For belongs to fields, you can link an task record to an already-existing related record by passing {_link: "<related record id>"} as the value for the field in your action.

Link to an existing parent
const taskRecord = await api.task.update("123", {
owner: {
_link: "456",
},
});
1const ExampleRunUpdateComponent = (props) => {
2 const [{ data, error, fetching }, update] = useAction(api.task.update);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await update({
9 id: "123",
10 owner: {
11 _link: "456",
12 },
13 });
14 }}
15 >
16 Run Action
17 </button>
18 Result: {JSON.stringify(data)}
19 </>
20 );
21};
1mutation UpdateTask($task: UpdateTaskInput, $id: GadgetID!) {
2 updateTask(task: $task, id: $id) {
3 success
4 errors {
5 message
6 ... on InvalidRecordError {
7 validationErrors {
8 apiIdentifier
9 message
10 }
11 record
12 model {
13 apiIdentifier
14 }
15 }
16 }
17 task {
18 __typename
19 id
20 state
21 createdAt
22 description {
23 markdown
24 truncatedHTML
25 }
26 ownerId
27 title
28 updatedAt
29 }
30 }
31}

Creating a linked child when creating a parent 

You can also create a new task record when creating a parent record by invoking the child create action as a nested action. Gadget will automatically link any records created in nested actions with their parent.

Create within an action on a parent
1const userRecord = await api.user.create({
2 tasks: [
3 {
4 create: {
5 description: {
6 markdown: "example _rich_ **text**",
7 },
8 title: "example value for title",
9 },
10 },
11 ],
12});
1const ExampleRunCreateComponent = (props) => {
2 const [{ data, error, fetching }, create] = useAction(api.user.create);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await create({
9 tasks: [
10 {
11 create: {
12 description: {
13 markdown: "example _rich_ **text**",
14 },
15 title: "example value for title",
16 },
17 },
18 ],
19 });
20 }}
21 >
22 Run Action
23 </button>
24 Result: {JSON.stringify(data)}
25 </>
26 );
27};
1mutation CreateUser($user: CreateUserInput) {
2 createUser(user: $user) {
3 success
4 errors {
5 message
6 ... on InvalidRecordError {
7 validationErrors {
8 apiIdentifier
9 message
10 }
11 record
12 model {
13 apiIdentifier
14 }
15 }
16 }
17 user {
18 __typename
19 id
20 state
21 createdAt
22 email
23 roles {
24 key
25 name
26 }
27 updatedAt
28 }
29 }
30}

Bulk Actions 

You can run the same action for an array of inputs all at once with bulk actions. Bulk Actions are executed as a single API call and offer better performance when running the same action on many records.

Creates, updates, deletes, and custom actions can all be run in bulk. Bulk Actions repeat the same action each time across a variety of different records. If you want to call different actions, you can't use Bulk Actions and must instead make multiple API calls.

If a bulk action group fails on some of the individual records, the remaining records will still be processed, and the list of errors will be returned in the result. Only the records which succeed in executing the action will be returned in the result.

Bulk task create 

Input 

bulkCreateTasks operates on a set of tasks, identified by the ids variable.

Example bulkCreateTasks Invocation
1const taskRecords = await api.task.bulkCreate([
2 {
3 description: {
4 markdown: "example _rich_ **text**",
5 },
6 title: "example value for title",
7 },
8 {
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 title: "example value for title",
13 },
14]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkCreate] = useBulkAction(api.task.bulkCreate);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkCreate([
9 {
10 description: {
11 markdown: "example _rich_ **text**",
12 },
13 title: "example value for title",
14 },
15 {
16 description: {
17 markdown: "example _rich_ **text**",
18 },
19 title: "example value for title",
20 },
21 ]);
22 console.log(data?.length); //=> a number
23 console.log(data?.[0].id); //=> a string
24 }}
25 >
26 Run Action
27 </button>
28 Result: {JSON.stringify(data)}
29 </>
30 );
31};
1mutation BulkCreateTasks($inputs: [BulkCreateTasksInput!]!) {
2 bulkCreateTasks(inputs: $inputs) {
3 success
4 errors {
5 message
6 }
7 tasks {
8 id
9 state
10 createdAt
11 description {
12 markdown
13 truncatedHTML
14 }
15 ownerId
16 title
17 updatedAt
18 }
19 }
20}
Variables
json
1{
2 "inputs": [
3 {
4 "task": {
5 "description": { "markdown": "example _rich_ **text**" },
6 "title": "example value for title"
7 }
8 },
9 {
10 "task": {
11 "description": { "markdown": "example _rich_ **text**" },
12 "title": "example value for title"
13 }
14 }
15 ]
16}
1const taskRecords = await api.task.bulkCreate([
2 {
3 description: {
4 markdown: "example _rich_ **text**",
5 },
6 title: "example value for title",
7 },
8 {
9 description: {
10 markdown: "example _rich_ **text**",
11 },
12 title: "example value for title",
13 },
14]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkCreate] = useBulkAction(api.task.bulkCreate);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkCreate([
9 {
10 description: {
11 markdown: "example _rich_ **text**",
12 },
13 title: "example value for title",
14 },
15 {
16 description: {
17 markdown: "example _rich_ **text**",
18 },
19 title: "example value for title",
20 },
21 ]);
22 console.log(data?.length); //=> a number
23 console.log(data?.[0].id); //=> a string
24 }}
25 >
26 Run Action
27 </button>
28 Result: {JSON.stringify(data)}
29 </>
30 );
31};
Output 

bulkCreateTasks returns the set of tasks that successfully completed the action. In the JS client, the fields returned for the record can be controlled with the select option. In GraphQL, the response is in the action result format, which includes a selection that completed the action successfully.The success property will be false if any of the records failed to perform their action and the returned set of tasks will only include the ones that completed successfully.

bulkCreateTasks Output Data
GraphQL
1"""
2The output when running the create on the task model in bulk.
3"""
4type BulkCreateTasksResult {
5 """
6 Boolean describing if all the bulk actions succeeded or not
7 """
8 success: Boolean!
9
10 """
11 Aggregated list of errors that any bulk action encountered while processing
12 """
13 errors: [ExecutionError!]
14
15 """
16 The list of all changed task records by each sent bulk action. Returned in the same order as the input bulk action params.
17 """
18 tasks: [Task]
19}

Bulk task update 

Input 

bulkUpdateTasks operates on a set of tasks, identified by the ids variable.

Example bulkUpdateTasks Invocation
1const taskRecords = await api.task.bulkUpdate([
2 {
3 description: {
4 markdown: "example _rich_ **text**",
5 },
6 id: "123",
7 owner: {
8 _link: "123",
9 },
10 },
11 {
12 description: {
13 markdown: "example _rich_ **text**",
14 },
15 id: "456",
16 owner: {
17 _link: "123",
18 },
19 },
20]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkUpdate] = useBulkAction(api.task.bulkUpdate);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkUpdate([
9 {
10 description: {
11 markdown: "example _rich_ **text**",
12 },
13 id: "123",
14 owner: {
15 _link: "123",
16 },
17 },
18 {
19 description: {
20 markdown: "example _rich_ **text**",
21 },
22 id: "456",
23 owner: {
24 _link: "123",
25 },
26 },
27 ]);
28 console.log(data?.length); //=> a number
29 console.log(data?.[0].id); //=> a string
30 }}
31 >
32 Run Action
33 </button>
34 Result: {JSON.stringify(data)}
35 </>
36 );
37};
1mutation BulkUpdateTasks($inputs: [BulkUpdateTasksInput!]!) {
2 bulkUpdateTasks(inputs: $inputs) {
3 success
4 errors {
5 message
6 }
7 tasks {
8 id
9 state
10 createdAt
11 description {
12 markdown
13 truncatedHTML
14 }
15 ownerId
16 title
17 updatedAt
18 }
19 }
20}
Variables
json
1{
2 "inputs": [
3 {
4 "task": {
5 "description": { "markdown": "example _rich_ **text**" },
6 "owner": { "_link": "123" }
7 },
8 "id": "123"
9 },
10 {
11 "task": {
12 "description": { "markdown": "example _rich_ **text**" },
13 "owner": { "_link": "123" }
14 },
15 "id": "456"
16 }
17 ]
18}
1const taskRecords = await api.task.bulkUpdate([
2 {
3 description: {
4 markdown: "example _rich_ **text**",
5 },
6 id: "123",
7 owner: {
8 _link: "123",
9 },
10 },
11 {
12 description: {
13 markdown: "example _rich_ **text**",
14 },
15 id: "456",
16 owner: {
17 _link: "123",
18 },
19 },
20]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkUpdate] = useBulkAction(api.task.bulkUpdate);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkUpdate([
9 {
10 description: {
11 markdown: "example _rich_ **text**",
12 },
13 id: "123",
14 owner: {
15 _link: "123",
16 },
17 },
18 {
19 description: {
20 markdown: "example _rich_ **text**",
21 },
22 id: "456",
23 owner: {
24 _link: "123",
25 },
26 },
27 ]);
28 console.log(data?.length); //=> a number
29 console.log(data?.[0].id); //=> a string
30 }}
31 >
32 Run Action
33 </button>
34 Result: {JSON.stringify(data)}
35 </>
36 );
37};
Output 

bulkUpdateTasks returns the set of tasks that successfully completed the action. In the JS client, the fields returned for the record can be controlled with the select option. In GraphQL, the response is in the action result format, which includes a selection that completed the action successfully.The success property will be false if any of the records failed to perform their action and the returned set of tasks will only include the ones that completed successfully.

bulkUpdateTasks Output Data
GraphQL
1"""
2The output when running the update on the task model in bulk.
3"""
4type BulkUpdateTasksResult {
5 """
6 Boolean describing if all the bulk actions succeeded or not
7 """
8 success: Boolean!
9
10 """
11 Aggregated list of errors that any bulk action encountered while processing
12 """
13 errors: [ExecutionError!]
14
15 """
16 The list of all changed task records by each sent bulk action. Returned in the same order as the input bulk action params.
17 """
18 tasks: [Task]
19}

Bulk task delete 

bulkDeleteTasks action destroys the records.

Input 

bulkDeleteTasks operates on a set of tasks, identified by the ids variable.

Example bulkDeleteTasks Invocation
await api.task.bulkDelete(["123", "456"]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkDelete] = useBulkAction(api.task.bulkDelete);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkDelete({
9 ids: ["123", "456"],
10 });
11 }}
12 >
13 Run Action
14 </button>
15 Result: {JSON.stringify(data)}
16 </>
17 );
18};
1mutation BulkDeleteTasks($ids: [GadgetID!]!) {
2 bulkDeleteTasks(ids: $ids) {
3 success
4 errors {
5 message
6 }
7 }
8}
Variables
json
{ "ids": ["123", "456"] }
await api.task.bulkDelete(["123", "456"]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkDelete] = useBulkAction(api.task.bulkDelete);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkDelete({
9 ids: ["123", "456"],
10 });
11 }}
12 >
13 Run Action
14 </button>
15 Result: {JSON.stringify(data)}
16 </>
17 );
18};
Output 

bulkDeleteTasks deletes the record, so it returns void in the JS client. In GraphQL it returns only the success and errors from the action result format.

bulkDeleteTasks Output Data
GraphQL
1"""
2The output when running the delete on the task model in bulk.
3"""
4type BulkDeleteTasksResult {
5 """
6 Boolean describing if all the bulk actions succeeded or not
7 """
8 success: Boolean!
9
10 """
11 Aggregated list of errors that any bulk action encountered while processing
12 """
13 errors: [ExecutionError!]
14}

Bulk task upsert 

Input 

bulkUpsertTasks operates on a set of tasks, identified by the ids variable.

Example bulkUpsertTasks Invocation
1const results = await api.task.bulkUpsert([
2 {
3 id: "123",
4 title: "example value for title",
5 },
6 {
7 id: "123",
8 title: "example value for title",
9 },
10]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkUpsert] = useBulkAction(api.task.bulkUpsert);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkUpsert([
9 {
10 id: "123",
11 title: "example value for title",
12 },
13 {
14 id: "123",
15 title: "example value for title",
16 },
17 ]);
18 console.log(data?.length); //=> a number
19 console.log(data?.[0].id); //=> a string
20 }}
21 >
22 Run Action
23 </button>
24 Result: {JSON.stringify(data)}
25 </>
26 );
27};
1mutation BulkUpsertTasks($inputs: [BulkUpsertTasksInput!]!) {
2 bulkUpsertTasks(inputs: $inputs) {
3 success
4 errors {
5 message
6 }
7 results
8 }
9}
Variables
json
1{
2 "inputs": [
3 { "task": { "id": "123", "title": "example value for title" } },
4 { "task": { "id": "123", "title": "example value for title" } }
5 ]
6}
1const results = await api.task.bulkUpsert([
2 {
3 id: "123",
4 title: "example value for title",
5 },
6 {
7 id: "123",
8 title: "example value for title",
9 },
10]);
1const RunActionComponent = (props) => {
2 const [{ data, error, fetching }, bulkUpsert] = useBulkAction(api.task.bulkUpsert);
3
4 return (
5 <>
6 <button
7 onClick={async () => {
8 await bulkUpsert([
9 {
10 id: "123",
11 title: "example value for title",
12 },
13 {
14 id: "123",
15 title: "example value for title",
16 },
17 ]);
18 console.log(data?.length); //=> a number
19 console.log(data?.[0].id); //=> a string
20 }}
21 >
22 Run Action
23 </button>
24 Result: {JSON.stringify(data)}
25 </>
26 );
27};
Output 

bulkUpsertTasks returns the set of tasks that successfully completed the action. In the JS client, the fields returned for the record can be controlled with the select option. In GraphQL, the response is in the action result format, which includes a selection that completed the action successfully.The success property will be false if any of the records failed to perform their action and the returned set of tasks will only include the ones that completed successfully.

bulkUpsertTasks Output Data
GraphQL
1"""
2The result of a bulk upsert operation for the task model
3"""
4type BulkUpsertTasksResult {
5 """
6 Boolean describing if all the bulk actions succeeded or not
7 """
8 success: Boolean!
9
10 """
11 Aggregated list of errors that any bulk action encountered while processing
12 """
13 errors: [ExecutionError!]
14
15 """
16 The results of each upsert action in the bulk operation
17 """
18 tasks: [Task]
19}

Was this page helpful?