User 

This page documents the user model.

Data Shape 

Gadget's database stores user 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 user:

user Schema
export type User = { __typename: 'User'; /** The globally unique, unchanging identifier for this record. Assigned and managed by Gadget. */ id: string; /** The time at which this record was first created. Set once upon record creation and never changed. Managed by Gadget. */ createdAt: Date; /** The time at which this record was last changed. Set each time the record is successfully acted upon by an action. Managed by Gadget. */ updatedAt: Date; /** The current state this record is in. Changed by invoking actions. Managed by Gadget. */ state: (string | { [key: string]: Scalars['RecordState'] }); email: string; roles: Role[]; sessions: SessionConnection; tasks: TaskConnection; /** Get all the fields for this record. Useful for not having to list out all the fields you want to retrieve, but slower. */ _all: Record<string, any>; };
type User { """ The globally unique, unchanging identifier for this record. Assigned and managed by Gadget. """ id: GadgetID! """ The time at which this record was first created. Set once upon record creation and never changed. Managed by Gadget. """ createdAt: DateTime! """ The time at which this record was last changed. Set each time the record is successfully acted upon by an action. Managed by Gadget. """ updatedAt: DateTime! """ The current state this record is in. Changed by invoking actions. Managed by Gadget. """ state: RecordState! email: String roles: [Role!] sessions( """ Returns the items in the list that come after the specified cursor. """ after: String """ Returns the first n items from the list. """ first: Int """ Returns the items in the list that come before the specified cursor. """ before: String """ Returns the last n items from the list. """ last: Int """ A list of filters to refine the results by """ filter: [SessionFilter!] ): SessionConnection! tasks( """ Returns the items in the list that come after the specified cursor. """ after: String """ Returns the first n items from the list. """ first: Int """ Returns the items in the list that come before the specified cursor. """ before: String """ Returns the last n items from the list. """ last: Int """ A list of sort orders to return the results in """ sort: [TaskSort!] """ A list of filters to refine the results by """ filter: [TaskFilter!] """ A free form text search query to find records matching """ search: String ): TaskConnection! """ Get all the fields for this record. Useful for not having to list out all the fields you want to retrieve, but slower. """ _all: JSONObject! }

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

Any fetched user record will have this same User 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 user record 

Individual user 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 user
const userRecord = await api.user.findOne("123"); // => a string console.log(userRecord.id); // => a Date object console.log(userRecord.createdAt);
const FindOneComponent = () => { const [{data, error, fetching}, refresh] = useFindOne(api.user, "123"); // => a string console.log(data?.id); // => a Date object console.log(data?.createdAt); return <>{JSON.stringify(data)}</>; };
query GetOneUser($id: GadgetID!) { user(id: $id) { __typename id state # ... createdAt email roles { key name } updatedAt } }
Variables
json
{ "id": "123" }
const userRecord = await api.user.findOne("123"); // => a string console.log(userRecord.id); // => a Date object console.log(userRecord.createdAt);
const FindOneComponent = () => { const [{data, error, fetching}, refresh] = useFindOne(api.user, "123"); // => a string console.log(data?.id); // => a Date object console.log(data?.createdAt); return <>{JSON.stringify(data)}</>; };

Retrieving the first of many user 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 user
const userRecord = await api.user.findFirst(); console.log(userRecord.id); //=> a string console.log(userRecord.createdAt); //=> a Date object
const FindFirstComponent = (props) => { const [{data, error, fetching}, refresh] = useFindFirst(api.user); // => a string console.log(data?.id) // => a Date object console.log(data?.createdAt) return <>{JSON.stringify(data)}</>; };
query FindManyUsers( $first: Int $search: String $sort: [UserSort!] $filter: [UserFilter!] ) { users(first: $first, search: $search, sort: $sort, filter: $filter) { edges { node { __typename id state # ... createdAt email roles { key name } updatedAt } } } }
Variables
json
{ "first": 1 }
const userRecord = await api.user.findFirst(); console.log(userRecord.id); //=> a string console.log(userRecord.createdAt); //=> a Date object
const FindFirstComponent = (props) => { const [{data, error, fetching}, refresh] = useFindFirst(api.user); // => a string console.log(data?.id) // => a Date object console.log(data?.createdAt) return <>{JSON.stringify(data)}</>; };

Retrieving many user records 

Pages of user 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 users 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 users 

You can fetch one page of records with the user.findMany JS method or the users 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 users
const userRecords = await api.user.findMany(); // => a number console.log(userRecords.length); // => a string console.log(userRecords[0].id);
const FindManyComponent = () => { const [{data, error, fetching}, refresh] = useFindMany(api.user); if (!data) return null; // => a number console.log(data.length) return <> {data.map(record => JSON.stringify(record))} </> };
query FindManyUsers( $after: String $before: String $first: Int $last: Int $search: String $sort: [UserSort!] $filter: [UserFilter!] ) { users( after: $after before: $before first: $first last: $last search: $search sort: $sort filter: $filter ) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{}
const userRecords = await api.user.findMany(); // => a number console.log(userRecords.length); // => a string console.log(userRecords[0].id);
const FindManyComponent = () => { const [{data, error, fetching}, refresh] = useFindMany(api.user); if (!data) return null; // => a number console.log(data.length) return <> {data.map(record => JSON.stringify(record))} </> };

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 has many data from the records linked by the sessions field using the select option:

Get related data from sessions
const userRecord = await api.user.findFirst({ select: { id: true, sessions: { edges: { node: { id: true, createdAt: true, }, }, }, }, }); console.log(userRecord.sessions?.map((edge) => edge.node.id)); //=> the related records' ids
const FindRelatedComponent = (props) => { const [{data, error, fetching}, refresh] = useFindFirst(api.user, { select: { id: true, sessions: { edges: { node: { id: true, createdAt: true } } } } }); if (!data) return null; // show the related records ids return <> {data.sessions?.map(edge => edge.node.id)} </> };
const userRecord = await api.user.findFirst({ select: { id: true, sessions: { edges: { node: { id: true, createdAt: true, }, }, }, }, }); console.log(userRecord.sessions?.map((edge) => edge.node.id)); //=> the related records' ids
const FindRelatedComponent = (props) => { const [{data, error, fetching}, refresh] = useFindFirst(api.user, { select: { id: true, sessions: { edges: { node: { id: true, createdAt: true } } } } }); if (!data) return null; // show the related records ids return <> {data.sessions?.map(edge => edge.node.id)} </> };

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 user 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 user record by id 

Individual user 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 users
const userRecord = await api.user.findById("some-value"); // => a string console.log(userRecord.id);
const FindByComponent = () => { const [{data, error, fetching}, refresh] = useFindBy(api.user.findById, "some-value"); // => a string console.log(data?.id); return <>{JSON.stringify(data)}</>; }
const userRecord = await api.user.findById("some-value"); // => a string console.log(userRecord.id);
const FindByComponent = () => { const [{data, error, fetching}, refresh] = useFindBy(api.user.findById, "some-value"); // => a string console.log(data?.id); return <>{JSON.stringify(data)}</>; }

Retrieving a single user record by email 

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

Find users
const userRecord = await api.user.findByEmail("some-value"); // => a string console.log(userRecord.id);
const FindByComponent = () => { const [{data, error, fetching}, refresh] = useFindBy(api.user.findByEmail, "some-value"); // => a string console.log(data?.id); return <>{JSON.stringify(data)}</>; }
const userRecord = await api.user.findByEmail("some-value"); // => a string console.log(userRecord.id);
const FindByComponent = () => { const [{data, error, fetching}, refresh] = useFindBy(api.user.findByEmail, "some-value"); // => a string console.log(data?.id); return <>{JSON.stringify(data)}</>; }

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 UserSort 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 UserSort 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 user by most recently created
const userRecords = await api.user.findMany({ sort: { createdAt: "Descending" } });
const [result, refresh] = useFindMany(api.user, { sort: { createdAt: "Descending" } }); const { data, error, fetching } = result;
query FindManyUsers($sort: [UserSort!]) { users(sort: $sort) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "sort": { "createdAt": "Descending" } }
const userRecords = await api.user.findMany({ sort: { createdAt: "Descending" } });
const [result, refresh] = useFindMany(api.user, { sort: { createdAt: "Descending" } }); const { data, error, fetching } = result;

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

Sort user by multiple fields
const userRecords = await api.user.findMany({ sort: [{ id: "Descending" }, { createdAt: "Ascending" }], });
const [result, refresh] = useFindMany(api.user, { sort: [ { id: "Descending" }, { createdAt: "Ascending" } ] }); const { data, error, fetching } = result;
query FindManyUsers($sort: [UserSort!]) { users(sort: $sort) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "sort": [{ "id": "Descending" }, { "createdAt": "Ascending" }] }
const userRecords = await api.user.findMany({ sort: [{ id: "Descending" }, { createdAt: "Ascending" }], });
const [result, refresh] = useFindMany(api.user, { sort: [ { id: "Descending" }, { createdAt: "Ascending" } ] }); const { data, error, fetching } = result;

Available fields for sorting 

You can sort user records by the following fields:

FieldSort type
idAscending / Descending
emailAscending / Descending
stateAscending / Descending
createdAtAscending / Descending
updatedAtAscending / Descending

For example, you can sort by the id field:

Sort users by id descending
const userRecords = await api.user.findMany({ sort: { id: "Descending" }, });
const [result, refresh] = useFindMany(api.user, { sort: { id: 'Descending'} }) const { data, error, fetching } = result;
query FindManyUsers($sort: [UserSort!]) { users(sort: $sort) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "sort": { "id": "Descending" } }
const userRecords = await api.user.findMany({ sort: { id: "Descending" }, });
const [result, refresh] = useFindMany(api.user, { sort: { id: 'Descending'} }) const { data, error, fetching } = result;

Read more about sorting in the Sorting and Filtering reference.

Searching 

user 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 Users by passing the search parameter with a search query string.

The search API is not supported on queries that also filter on related model fields .

Search isn't field specific in Gadget -- all of the following field types are searched with the built in search functionality:

  • id
  • string
  • number
  • enum
  • rich text
  • date / time
  • email
  • url
  • boolean
  • json
  • record state
  • role list
  • belongs to (searches on the related record ID)
Full text search Users
const userRecords = await api.user.findMany({ search: "a specific phrase to search for", });
const [result, refresh] = useFindMany(api.user, { search: "a specific phrase to search for", }); const { data, error, fetching } = result;
query FindManyUsers($search: String) { users(search: $search) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "search": "a specific phrase to search for" }
const userRecords = await api.user.findMany({ search: "a specific phrase to search for", });

Filtering 

user 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 Users 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 Users created in the last day
const yesterday = new Date(Date.now() - 86400000); const userRecords = await api.user.findMany({ filter: { createdAt: { greaterThan: yesterday } }, });
const yesterday = new Date(Date.now() - 86400000); const [result, refresh] = useFindMany(api.user, { filter: { createdAt: { greaterThan: yesterday }} }) const { data, error, fetching } = result;
query FindManyUsers($filter: [UserFilter!]) { users(filter: $filter) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "filter": { "createdAt": { "greaterThan": "2025-04-25T16:10:05.977Z" } } }
const yesterday = new Date(Date.now() - 86400000); const userRecords = await api.user.findMany({ filter: { createdAt: { greaterThan: yesterday } }, });
const yesterday = new Date(Date.now() - 86400000); const [result, refresh] = useFindMany(api.user, { filter: { createdAt: { greaterThan: yesterday }} }) const { data, error, fetching } = result;

Available fields for filtering 

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

Field

Filter type

idIDFilter
emailEmailFilter
stateRecordStateFilter
rolesRoleAssignmentsFilter
createdAtDateTimeFilter
updatedAtDateTimeFilter

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

const userRecords = await api.user.findMany({ filter: { id: { isSet: true }, }, });
const [result, refresh] = useFindMany(api.user, { filter: { id: {isSet: true} } }) const { data, error, fetching } = result;
query FindManyUsers($filter: [UserFilter!]) { users(filter: $filter) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "filter": { "id": { "isSet": true } } }
const userRecords = await api.user.findMany({ filter: { id: { isSet: true }, }, });
const [result, refresh] = useFindMany(api.user, { filter: { id: {isSet: true} } }) const { 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.

Users created this week or updated today
const yesterday = new Date(Date.now() - 86400000); const oneWeekAgo = new Date(Date.now() - 604800000); const userRecords = await api.user.findMany({ filter: { OR: [ { createdAt: { greaterThan: oneWeekAgo }, }, { updatedAt: { greaterThan: yesterday }, }, ], }, });
const yesterday = new Date(Date.now() - 86400000); const oneWeekAgo = new Date(Date.now() - 604800000); const [result, refresh] = useFindMany(api.user, { filter: { OR: [ { createdAt: { greaterThan: oneWeekAgo }, }, { updatedAt: { greaterThan: yesterday }, }, ] } }) const { data, error, fetching } = result;
query FindManyUsers($filter: [UserFilter!]) { users(filter: $filter) { edges { node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "filter": { "OR": [ { "createdAt": { "greaterThan": "2025-04-19T16:10:05.981Z" } }, { "updatedAt": { "greaterThan": "2025-04-25T16:10:05.981Z" } } ] } }
const yesterday = new Date(Date.now() - 86400000); const oneWeekAgo = new Date(Date.now() - 604800000); const userRecords = await api.user.findMany({ filter: { OR: [ { createdAt: { greaterThan: oneWeekAgo }, }, { updatedAt: { greaterThan: yesterday }, }, ], }, });
const yesterday = new Date(Date.now() - 86400000); const oneWeekAgo = new Date(Date.now() - 604800000); const [result, refresh] = useFindMany(api.user, { filter: { OR: [ { createdAt: { greaterThan: oneWeekAgo }, }, { updatedAt: { greaterThan: yesterday }, }, ] } }) const { data, error, fetching } = result;

Pagination 

All Gadget record lists, including the top level user finder as well as associations to user, 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 user 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.

user 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 users
const userRecords = await api.user.findMany({ first: 25 }); // => no greater than 25 console.log(userRecords.length);
const FirstPage = () => { const [{ data, error, fetching }, refresh] = useFindMany(api.user, {first: 25}) if (!data) return null; // => no greater than 25 console.log(data.length); return <> {data.map(record => JSON.stringify(record))} </> }
query FindManyUsers($first: Int, $after: String) { users(first: $first, after: $after) { pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { cursor node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "first": 25 }
const userRecords = await api.user.findMany({ first: 25 }); // => no greater than 25 console.log(userRecords.length);
const FirstPage = () => { const [{ data, error, fetching }, refresh] = useFindMany(api.user, {first: 25}) if (!data) return null; // => no greater than 25 console.log(data.length); return <> {data.map(record => JSON.stringify(record))} </> }
Next 25 user records after cursor
const userRecords = await api.user.findMany({ after: "example-cursor", first: 25 });
const SecondPage = (props) => { const [{ data, error, fetching }, refresh] = useFindMany(api.user, {after: "example-cursor", first: 25}); if (!data) return null; // => no greater than 25 console.log(data.length); return <> {data.map(record => JSON.stringify(record))} </> }
query FindManyUsers($first: Int, $after: String) { users(first: $first, after: $after) { pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { cursor node { __typename id state # ... createdAt updatedAt } } } }
Variables
json
{ "first": 25, "after": "abcdefg" }
const userRecords = await api.user.findMany({ after: "example-cursor", first: 25 });
const SecondPage = (props) => { const [{ data, error, fetching }, refresh] = useFindMany(api.user, {after: "example-cursor", first: 25}); if (!data) return null; // => no greater than 25 console.log(data.length); return <> {data.map(record => JSON.stringify(record))} </> }

Pagination Limits 

Root-level record finders like users 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
const userRecords = await api.user.findMany(); if (userRecords.hasNextPage) { const nextPage = await userRecords.nextPage(); } if (userRecords.hasPreviousPage) { const prevPage = await userRecords.previousPage(); }
const userRecords = await api.user.findMany(); if (userRecords.hasNextPage) { const nextPage = await userRecords.nextPage(); } if (userRecords.hasPreviousPage) { const prevPage = await userRecords.previousPage(); }

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 user.

React
// your Gadget project's API Client import { api } from "../api"; import { useFindMany } from "@gadgetinc/react"; import { useCallback, useState } from "react"; export default function TestComponent() { // the number of records per page const NUM_ON_PAGE = 2; const [cursor, setCursor] = useState({ first: NUM_ON_PAGE }); // using Gadget React hooks to fetch records of user const [{ data, fetching, error }] = useFindMany(api.user, { ...cursor, }); const getNextPage = useCallback(() => { // use first + after to page forwards setCursor({ first: NUM_ON_PAGE, after: data.endCursor }); }, [data]); const getPreviousPage = useCallback(() => { // use last + before to page backwards setCursor({ last: NUM_ON_PAGE, before: data.startCursor }); }, [data]); return ( <div> <button onClick={getPreviousPage} disabled={!data?.hasPreviousPage}> Previous page </button> <button onClick={getNextPage} disabled={!data?.hasNextPage}> Next page </button> {!fetching && data.map((d) => <div>{d.id}</div>)} </div> ); }
// your Gadget project's API Client import { api } from "../api"; import { useFindMany } from "@gadgetinc/react"; import { useCallback, useState } from "react"; export default function TestComponent() { // the number of records per page const NUM_ON_PAGE = 2; const [cursor, setCursor] = useState({ first: NUM_ON_PAGE }); // using Gadget React hooks to fetch records of user const [{ data, fetching, error }] = useFindMany(api.user, { ...cursor, }); const getNextPage = useCallback(() => { // use first + after to page forwards setCursor({ first: NUM_ON_PAGE, after: data.endCursor }); }, [data]); const getPreviousPage = useCallback(() => { // use last + before to page backwards setCursor({ last: NUM_ON_PAGE, before: data.startCursor }); }, [data]); return ( <div> <button onClick={getPreviousPage} disabled={!data?.hasPreviousPage}> Previous page </button> <button onClick={getNextPage} disabled={!data?.hasNextPage}> Next page </button> {!fetching && data.map((d) => <div>{d.id}</div>)} </div> ); }

Get all records 

If you need to get all available data for user, 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
// use allRecords to store all records const allRecords = []; let records = await api.user.findMany({ first: 250, select: { id: true, }, filter: { // add filter conditions, if possible }, }); allRecords.push(...records); // loop through additional pages to get all protected orders while (records.hasNextPage) { // paginate records = await records.nextPage(); allRecords.push(...records); }
// use allRecords to store all records const allRecords = []; let records = await api.user.findMany({ first: 250, select: { id: true, }, filter: { // add filter conditions, if possible }, }); allRecords.push(...records); // loop through additional pages to get all protected orders while (records.hasNextPage) { // paginate records = await records.nextPage(); allRecords.push(...records); }

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 user 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 user. If you don't pass a select option to a record finder, this default selection will be used.

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

If you want to include the ID of a belongs to or has one relationship in your response, you can add the ID of the relationship field to the select parameter. For example, say we have a ticket model that belongs to a flight model. We can get the flight that the ticket is associated with like so:

Get associated flight ID
JavaScript
const [{ data, fetching, error }, _refetch] = useFindMany(api.ticket, { select: { id: true, ticketNumber: true, flightId: true }, });
const [{ data, fetching, error }, _refetch] = useFindMany(api.ticket, { select: { id: true, ticketNumber: true, flightId: true }, });

Where flight is the name of the relationship field on the ticket model. You must append Id in camel case. If flightId is not included in the select statement, it will not be part of the returned object.

Realtime subscriptions with live queries 

Each read function in the user 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 user 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.user.findOne("123", { live: true })) { // record will be a GadgetRecord object console.log("new record version", record); }
export const Record123 = (props) => { const [{data, error, fetching}] = useFindOne(api.user, "123", // the id of the record to fetch { // make this a realtime live query live: true, }); if (!data) return null; return ( <div> Record 123 last updated at {data.updatedAt} </div> ); }
// calling findOne with live: true will return a stream of results as an AsyncIterator, not just one result for await (const record of api.user.findOne("123", { live: true })) { // record will be a GadgetRecord object console.log("new record version", record); }
export const Record123 = (props) => { const [{data, error, fetching}] = useFindOne(api.user, "123", // the id of the record to fetch { // make this a realtime live query live: true, }); if (!data) return null; return ( <div> Record 123 last updated at {data.updatedAt} </div> ); }

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

First 10 user 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.user.findMany({ live: true, first: 10 })) { // list will be an array of GadgetRecord objects console.log("new query result", list); }
export const FirstPage = (props) => { const [{data, error, fetching}] = useFindMany(api.user, { // make this a realtime live query live: true, first: 10 }); if (!data) return null; return ( <div> {data.map((record) => ( <div key={record.id}>{record.id}</div> ))} </div> ); }
// calling findMany with live: true will return a stream of results as an AsyncIterator, not just one result for await (const list of api.user.findMany({ live: true, first: 10 })) { // list will be an array of GadgetRecord objects console.log("new query result", list); }
export const FirstPage = (props) => { const [{data, error, fetching}] = useFindMany(api.user, { // make this a realtime live query live: true, first: 10 }); if (!data) return null; return ( <div> {data.map((record) => ( <div key={record.id}>{record.id}</div> ))} </div> ); }

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 user fields
// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject` const userRecords = await api.user.findMany({ select: { id: true, createdAt: true, someRelatedObject: { id: true, createdAt: true }, }, });
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.user, {select: { id: true, createdAt: true, someRelatedObject: { id: true, createdAt: true } }}); // ... }
// fetch the id and createdAt field, and fetch some nested fields from an example relationship field named `someRelatedObject` const userRecords = await api.user.findMany({ select: { id: true, createdAt: true, someRelatedObject: { id: true, createdAt: true }, }, });
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.user, {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
const userRecords = await api.user.findMany({ search: "<some search query>", sort: { createdAt: "Descending" }, filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000) } }, select: { id: true, createdAt: true }, first: 25, after: "abcdefg", });
const [result, refresh] = useFindMany(api.user, { search: "<some search query>", sort: { createdAt: "Descending" }, filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000)}}, select: { id: true, createdAt: true }, first: 25, after: "abcdefg" }); const { data, error, fetching } = result;
query FindManyUsers( $after: String $before: String $first: Int $last: Int $search: String $sort: [UserSort!] $filter: [UserFilter!] ) { users( after: $after before: $before first: $first last: $last search: $search sort: $sort filter: $filter ) { edges { node { __typename id state # ... createdAt email roles { key name } updatedAt } } } }
Variables
json
{ "search": "<some search query>", "sort": { "createdAt": "Descending" }, "filter": { "updatedAt": { "greaterThan": "2025-04-25T16:10:06.033Z" } }, "first": 25, "after": "abcdefg" }
const userRecords = await api.user.findMany({ search: "<some search query>", sort: { createdAt: "Descending" }, filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000) } }, select: { id: true, createdAt: true }, first: 25, after: "abcdefg", });
const [result, refresh] = useFindMany(api.user, { search: "<some search query>", sort: { createdAt: "Descending" }, filter: { updatedAt: { greaterThan: new Date(Date.now() - 86400000)}}, select: { id: true, createdAt: true }, first: 25, after: "abcdefg" }); const { data, error, fetching } = result;

Invoking Actions 

user 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
import { GadgetOperationError, InvalidRecordError, } from "@gadgetinc/api-client-core"; // must be in an async function to use await` syntax export async function run({ api }) { try { return await api.exampleModel.create({ name: "example record name" }); } catch (error) { if (error instanceof GadgetOperationError) { // a recognized general error has occurred, retry the operation or inspect \error.code\` console.error(error); } else if (error instanceof InvalidRecordError) { // the submitted input data for the action was invalid, inspect the invalid fields which \`InvalidRecordError\` exposes console.error(error.validationErrors); } else { // 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 throw error; } } }
import { GadgetOperationError, InvalidRecordError, } from "@gadgetinc/api-client-core"; // must be in an async function to use await` syntax export async function run({ api }) { try { return await api.exampleModel.create({ name: "example record name" }); } catch (error) { if (error instanceof GadgetOperationError) { // a recognized general error has occurred, retry the operation or inspect \error.code\` console.error(error); } else if (error instanceof InvalidRecordError) { // the submitted input data for the action was invalid, inspect the invalid fields which \`InvalidRecordError\` exposes console.error(error.validationErrors); } else { // 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 throw error; } } }

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

user signUp 

Input 

signUp accepts the following input parameters:

signUp Input Data
export type SignUpUserInput = { email?: (Scalars['String'] | null) | null; password?: (Scalars['String'] | null) | null; sessions?: (SessionHasManyInput | null)[]; tasks?: (TaskHasManyInput | null)[]; }; export type SignUpUserArguments = { user?: SignUpUserInput | null; };
input SignUpUserInput { email: String password: String sessions: [SessionHasManyInput] tasks: [TaskHasManyInput] } input SignUpUserArguments { user: SignUpUserInput }
Example signUp Invocation
const userRecord = await api.user.signUp({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunSignUpComponent = () => { const [{ data, error, fetching }, signUp] = useAction(api.user.signUp); return ( <> <button onClick={async () => { await signUp({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation SignUpUser($user: SignUpUserInput) { signUpUser(user: $user) { success errors { message ... on InvalidRecordError { validationErrors { apiIdentifier message } record model { apiIdentifier } } } user { __typename id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "user": { "email": "[email protected]", "password": "nohacking123%", "roles": ["signed-in"] } }
const userRecord = await api.user.signUp({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunSignUpComponent = () => { const [{ data, error, fetching }, signUp] = useAction(api.user.signUp); return ( <> <button onClick={async () => { await signUp({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

signUp returns the user. 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.

signUp Output Data
GraphQL
type SignUpUserResult { success: Boolean! errors: [ExecutionError!] actionRun: String user: User }

user update 

Input 

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

update Input Data
export type UpdateUserInput = { email?: (Scalars['String'] | null) | null; password?: (Scalars['String'] | null) | null; sessions?: (SessionHasManyInput | null)[]; tasks?: (TaskHasManyInput | null)[]; }; export type UpdateUserArguments = { user?: UpdateUserInput | null; };
input UpdateUserInput { email: String password: String sessions: [SessionHasManyInput] tasks: [TaskHasManyInput] } input UpdateUserArguments { user: UpdateUserInput }
Example update Invocation
const userRecord = await api.user.update("1", { email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunUpdateComponent = () => { const [{ data, error, fetching }, update] = useAction(api.user.update); return ( <> <button onClick={async () => { await update({ email: "[email protected]", id: "1", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation UpdateUser($user: UpdateUserInput, $id: GadgetID!) { updateUser(user: $user, id: $id) { success errors { message ... on InvalidRecordError { validationErrors { apiIdentifier message } record model { apiIdentifier } } } user { __typename id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "user": { "email": "[email protected]", "password": "nohacking123%", "roles": ["signed-in"] }, "id": "1" }
const userRecord = await api.user.update("1", { email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunUpdateComponent = () => { const [{ data, error, fetching }, update] = useAction(api.user.update); return ( <> <button onClick={async () => { await update({ email: "[email protected]", id: "1", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

update returns the user. 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
type UpdateUserResult implements UpsertUserResult { success: Boolean! errors: [ExecutionError!] actionRun: String user: User }

user delete 

The delete action destroys the record.

Input 

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

Example delete Invocation
await api.user.delete("1");
const ExampleRunDeleteComponent = () => { const [{ data, error, fetching }, _delete] = useAction(api.user.delete); return ( <> <button onClick={async () => { await _delete({ id: "1", }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation DeleteUser($id: GadgetID!) { deleteUser(id: $id) { success errors { message ... on InvalidRecordError { validationErrors { apiIdentifier message } record model { apiIdentifier } } } } }
Variables
json
{ "id": "1" }
await api.user.delete("1");
const ExampleRunDeleteComponent = () => { const [{ data, error, fetching }, _delete] = useAction(api.user.delete); return ( <> <button onClick={async () => { await _delete({ id: "1", }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
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 DeleteUserResult { success: Boolean! errors: [ExecutionError!] actionRun: String }

user create 

Input 

create accepts the following input parameters:

create Input Data
export type CreateUserInput = { email?: (Scalars['String'] | null) | null; password?: (Scalars['String'] | null) | null; sessions?: (SessionHasManyInput | null)[]; tasks?: (TaskHasManyInput | null)[]; }; export type CreateUserArguments = { user?: CreateUserInput | null; };
input CreateUserInput { email: String password: String sessions: [SessionHasManyInput] tasks: [TaskHasManyInput] } input CreateUserArguments { user: CreateUserInput }
Example create Invocation
const userRecord = await api.user.create({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunCreateComponent = () => { const [{ data, error, fetching }, create] = useAction(api.user.create); return ( <> <button onClick={async () => { await create({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation CreateUser($user: CreateUserInput) { createUser(user: $user) { success errors { message ... on InvalidRecordError { validationErrors { apiIdentifier message } record model { apiIdentifier } } } user { __typename id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "user": { "email": "[email protected]", "password": "nohacking123%", "roles": ["signed-in"] } }
const userRecord = await api.user.create({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunCreateComponent = () => { const [{ data, error, fetching }, create] = useAction(api.user.create); return ( <> <button onClick={async () => { await create({ email: "[email protected]", password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

create returns the user. 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
type CreateUserResult implements UpsertUserResult { success: Boolean! errors: [ExecutionError!] actionRun: String user: User }

user upsert 

Input 

upsert accepts the following input parameters:

upsert Input Data
export type UpsertUserInput = { id?: (Scalars['GadgetID'] | null) | null; email?: (Scalars['String'] | null) | null; password?: (Scalars['String'] | null) | null; /** A string list of Gadget platform Role keys to assign to this record */ roles?: ((Scalars['String'] | null))[]; sessions?: (SessionHasManyInput | null)[]; tasks?: (TaskHasManyInput | null)[]; }; export type UpsertUserArguments = { /** An array of Strings */ on?: ((Scalars['String'] | null))[]; user?: UpsertUserInput | null; };
input UpsertUserInput { id: GadgetID email: String password: String """ A string list of Gadget platform Role keys to assign to this record """ roles: [String!] sessions: [SessionHasManyInput] tasks: [TaskHasManyInput] } input UpsertUserArguments { """ An array of Strings """ on: [String!] user: UpsertUserInput }
Example upsert Invocation
const result = await api.user.upsert({ email: "[email protected]", id: "1", on: ["email"], password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunUpsertComponent = () => { const [{ data, error, fetching }, upsert] = useAction(api.user.upsert); return ( <> <button onClick={async () => { await upsert({ email: "[email protected]", id: "1", on: ["email"], password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation UpsertUser($on: [String!], $user: UpsertUserInput) { upsertUser(on: $on, user: $user) { success errors { message } } }
Variables
json
{ "on": ["email"], "user": { "email": "[email protected]", "id": "1", "password": "nohacking123%", "roles": ["signed-in"] } }
const result = await api.user.upsert({ email: "[email protected]", id: "1", on: ["email"], password: "nohacking123%", roles: ["signed-in"], });
const ExampleRunUpsertComponent = () => { const [{ data, error, fetching }, upsert] = useAction(api.user.upsert); return ( <> <button onClick={async () => { await upsert({ email: "[email protected]", id: "1", on: ["email"], password: "nohacking123%", roles: ["signed-in"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

upsert returns the user. 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 UpsertUserResult { success: Boolean! errors: [ExecutionError!] actionRun: String }

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

Linking existing child records 

For has many fields, actions on user records can also update child records to link to this record. You can link existing child records by passing a nested action to invoke on the child record. Gadget will implicitly link the referenced child record to the outer parent record in the API call.

Linking to a new child record 

You can also nest actions on child records to create new children when running actions on the parent. Pass a nestedcreate action for the child record, and Gadget will implicitly link it to the outer parent record in your API call.

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 user signUp 

Input 

bulkSignUpUsers operates on a set of users, identified by the ids variable.

Example bulkSignUpUsers Invocation
const userRecords = await api.user.bulkSignUp([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkSignUp] = useBulkAction(api.user.bulkSignUp); return ( <> <button onClick={async () => { await bulkSignUp([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation BulkSignUpUsers($inputs: [BulkSignUpUsersInput!]!) { bulkSignUpUsers(inputs: $inputs) { success errors { message } users { id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "inputs": [ { "user": { "email": "[email protected]", "password": "nohacking123%" } }, { "user": { "email": "[email protected]", "password": "nohacking123%" } } ] }
const userRecords = await api.user.bulkSignUp([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkSignUp] = useBulkAction(api.user.bulkSignUp); return ( <> <button onClick={async () => { await bulkSignUp([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

bulkSignUpUsers returns the set of users 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 users will only include the ones that completed successfully.

bulkSignUpUsers Output Data
GraphQL
""" The output when running the signUp on the user model in bulk. """ type BulkSignUpUsersResult { """ Boolean describing if all the bulk actions succeeded or not """ success: Boolean! """ Aggregated list of errors that any bulk action encountered while processing """ errors: [ExecutionError!] """ The list of all changed user records by each sent bulk action. Returned in the same order as the input bulk action params. """ users: [User] }

Bulk user update 

Input 

bulkUpdateUsers operates on a set of users, identified by the ids variable.

Example bulkUpdateUsers Invocation
const userRecords = await api.user.bulkUpdate([ { email: "[email protected]", id: "1", password: "nohacking123%", }, { email: "[email protected]", id: "2", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkUpdate] = useBulkAction(api.user.bulkUpdate); return ( <> <button onClick={async () => { await bulkUpdate([ { email: "[email protected]", id: "1", password: "nohacking123%", }, { email: "[email protected]", id: "2", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation BulkUpdateUsers($inputs: [BulkUpdateUsersInput!]!) { bulkUpdateUsers(inputs: $inputs) { success errors { message } users { id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "inputs": [ { "user": { "email": "[email protected]", "password": "nohacking123%" }, "id": "1" }, { "user": { "email": "[email protected]", "password": "nohacking123%" }, "id": "2" } ] }
const userRecords = await api.user.bulkUpdate([ { email: "[email protected]", id: "1", password: "nohacking123%", }, { email: "[email protected]", id: "2", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkUpdate] = useBulkAction(api.user.bulkUpdate); return ( <> <button onClick={async () => { await bulkUpdate([ { email: "[email protected]", id: "1", password: "nohacking123%", }, { email: "[email protected]", id: "2", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

bulkUpdateUsers returns the set of users 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 users will only include the ones that completed successfully.

bulkUpdateUsers Output Data
GraphQL
""" The output when running the update on the user model in bulk. """ type BulkUpdateUsersResult { """ Boolean describing if all the bulk actions succeeded or not """ success: Boolean! """ Aggregated list of errors that any bulk action encountered while processing """ errors: [ExecutionError!] """ The list of all changed user records by each sent bulk action. Returned in the same order as the input bulk action params. """ users: [User] }

Bulk user delete 

bulkDeleteUsers action destroys the records.

Input 

bulkDeleteUsers operates on a set of users, identified by the ids variable.

Example bulkDeleteUsers Invocation
await api.user.bulkDelete(["1", "2"]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkDelete] = useBulkAction(api.user.bulkDelete); return ( <> <button onClick={async () => { await bulkDelete({ ids: ["1", "2"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation BulkDeleteUsers($ids: [GadgetID!]!) { bulkDeleteUsers(ids: $ids) { success errors { message } } }
Variables
json
{ "ids": ["1", "2"] }
await api.user.bulkDelete(["1", "2"]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkDelete] = useBulkAction(api.user.bulkDelete); return ( <> <button onClick={async () => { await bulkDelete({ ids: ["1", "2"], }); }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

bulkDeleteUsers 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.

bulkDeleteUsers Output Data
GraphQL
""" The output when running the delete on the user model in bulk. """ type BulkDeleteUsersResult { """ Boolean describing if all the bulk actions succeeded or not """ success: Boolean! """ Aggregated list of errors that any bulk action encountered while processing """ errors: [ExecutionError!] }

Bulk user create 

Input 

bulkCreateUsers operates on a set of users, identified by the ids variable.

Example bulkCreateUsers Invocation
const userRecords = await api.user.bulkCreate([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkCreate] = useBulkAction(api.user.bulkCreate); return ( <> <button onClick={async () => { await bulkCreate([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation BulkCreateUsers($inputs: [BulkCreateUsersInput!]!) { bulkCreateUsers(inputs: $inputs) { success errors { message } users { id state createdAt email roles { key name } updatedAt } } }
Variables
json
{ "inputs": [ { "user": { "email": "[email protected]", "password": "nohacking123%" } }, { "user": { "email": "[email protected]", "password": "nohacking123%" } } ] }
const userRecords = await api.user.bulkCreate([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkCreate] = useBulkAction(api.user.bulkCreate); return ( <> <button onClick={async () => { await bulkCreate([ { email: "[email protected]", password: "nohacking123%", }, { email: "[email protected]", password: "nohacking123%", }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

bulkCreateUsers returns the set of users 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 users will only include the ones that completed successfully.

bulkCreateUsers Output Data
GraphQL
""" The output when running the create on the user model in bulk. """ type BulkCreateUsersResult { """ Boolean describing if all the bulk actions succeeded or not """ success: Boolean! """ Aggregated list of errors that any bulk action encountered while processing """ errors: [ExecutionError!] """ The list of all changed user records by each sent bulk action. Returned in the same order as the input bulk action params. """ users: [User] }

Bulk user upsert 

Input 

bulkUpsertUsers operates on a set of users, identified by the ids variable.

Example bulkUpsertUsers Invocation
const results = await api.user.bulkUpsert([ { email: "[email protected]", id: "1", on: ["email"], }, { email: "[email protected]", id: "1", on: ["email"], }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkUpsert] = useBulkAction(api.user.bulkUpsert); return ( <> <button onClick={async () => { await bulkUpsert([ { email: "[email protected]", id: "1", on: ["email"], }, { email: "[email protected]", id: "1", on: ["email"], }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
mutation BulkUpsertUsers($inputs: [BulkUpsertUsersInput!]!) { bulkUpsertUsers(inputs: $inputs) { success errors { message } results } }
Variables
json
{ "inputs": [ { "on": ["email"], "user": { "email": "[email protected]", "id": "1" } }, { "on": ["email"], "user": { "email": "[email protected]", "id": "1" } } ] }
const results = await api.user.bulkUpsert([ { email: "[email protected]", id: "1", on: ["email"], }, { email: "[email protected]", id: "1", on: ["email"], }, ]);
const RunActionComponent = () => { const [{ data, error, fetching }, bulkUpsert] = useBulkAction(api.user.bulkUpsert); return ( <> <button onClick={async () => { await bulkUpsert([ { email: "[email protected]", id: "1", on: ["email"], }, { email: "[email protected]", id: "1", on: ["email"], }, ]); console.log(data?.length); //=> a number console.log(data?.[0].id); //=> a string }} > Run Action </button> Result: {JSON.stringify(data)} </> ); };
Output 

bulkUpsertUsers returns the set of users 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 users will only include the ones that completed successfully.

bulkUpsertUsers Output Data
GraphQL
""" The result of a bulk upsert operation for the user model """ type BulkUpsertUsersResult { """ Boolean describing if all the bulk actions succeeded or not """ success: Boolean! """ Aggregated list of errors that any bulk action encountered while processing """ errors: [ExecutionError!] """ The results of each upsert action in the bulk operation """ users: [User] }

Was this page helpful?