API
Select a Trigger datatype to view its API
Table
Tables are the backbone of Trigger and offer unique experiences compared to other React state management libraries. The following methods are available for interacting with your tables once created.- use()
- useById()
- useLoadData()
- find()
- findOne()
- findById()
- scan()
- count()
- insertOne()
- insertMany()
- onBeforeInsert()
- onAfterInsert()
- deleteOne()
- deleteById()
- deleteMany()
- onBeforeDelete()
- onAfterDelete()
- updateById()
- updateMany()
- onBeforeUpdate()
- onAfterUpdate()
- columnNames()
- print()
- toJSON()
Retrieves rows from the specified table and rerenders your component. If notify is ommitted, the component will rerender for all events on the specified table. Supported notify events are: 'onInsert' | 'onUpdate' | 'onDelete'. If a filtering function is not provided to the where parameter, this will return all rows in the table.
use(where?: Partial<T> | ((row: TableRow<T>) => boolean) | null, notify?: ['onInsert' | 'onUpdate' | 'onDelete']): TableRow<T>[]
- where (optional) (
Partial<T> | (row: TableRow<T>) => boolean) | null
): receives an object to match rows based on equality of each property value, a function, null, or undefined. If a function is provided, it will receive each value in the table, allowing you to filter the table as needed. Omitting or passing undefined, will return all rows. Passing null will also return all rows, but it allows you to set the notify parameter - notify (optional) (
['onInsert' | 'onUpdate' | 'onDelete']
): allows the user to specify which table events will cause the component to rerender. If omitted, the rows will be retrieved and the component rerendered everytime there is a change to any row in the table.
// returns all rows from the cats table
// will rerender the component whenever any change occurs to the table
import { tables } from './store';
const rows = tables.cats.use();
// returns all rows from the cats table where the name is "Cleo"
// will rerender the component whenever a new row is inserted or deleted
import { tables } from './store';
const rows = tables.cats.use(row => row.name === 'Cleo', ['onInsert', 'onDelete']);
Retrieves a row from the specified table and rerenders your component. If notify is ommitted, the component will rerender for all events on the specified row. Supported notify events are: 'onUpdate' | 'onDelete'.
useById(_id: number, notify?: ['onUpdate', 'onDelete']): TableRow<T> | undefined
- _id (
number
): the autogenerated _id for the row you would like to retrieve - notify (optional) (
['onUpdate' | 'onDelete']
): allows the user to specify which row events will cause the component to rerender. If omitted, the component will rerender whenever the row is updated or deleted.
// returns the row with an autogenerated _id entry of 10
// will rerender the component whenever the row is updated or deleted
import { tables } from './store';
const row = tables.cats.useById(10);
// returns the row with an autogenerated _id entry of 10
// will rerender the component whenever the row is updated
import { tables } from './store';
const row = tables.cats.useById(10, ['onUpdate']);
Receives a query function and loads the data into the specified table, returning the data, status, and any error messages.
useLoadData(queryFn: () => Promise<T[]> | undefined, options?: object): { data: TableRow<T>[]; status: FetchStatus; error: string | null };
- queryFn (
() => Promise<T[]> | undefined
): a function that returns a promise with the data to be loaded into the database, or undefined if data should not be retrieved. - options (optional) (
object
):- refreshOn (optional) (
unknown[]
): user-provided values that when changed will cause the data to refresh - refreshMode (optional) (
'replace' | 'append'
): default value is 'replace'. When the data is refreshed, 'replace' will remove all existing data and insert the new data, 'append' will keep the existing data and add the new data to the table - resetIndex (optional) (
boolean
): default value is 'false'. Setting to true will reset the table's autoincrementing _id back to 0 when the data is refreshed and the refreshMode is 'replace' - notify (optional) (
['onInsert' | 'onUpdate' | 'onDelete']
): default is to notify for all table events. Allows the user to specify which table events will cause the component to rerender. If omitted, the rows will be retrieved and the component rerendered everytime there is a change to any row in the table. - fetchOnMount (optional) (
boolean
): default value is 'true'. Setting to true will call the query function and load the data each time the component mounts. - onSuccess (optional) (
() => void)
): a function that is fired after the data is successfully loaded. This is convenient for setting a value in your store to indicate the data has already been loaded. - filter (optional) (
(row: TableRow
)): filters the data returned to the component after all of the data has been loaded to the table.) => boolean)
- refreshOn (optional) (
['idle', 'error', 'loading', 'success']
), and an error message if applicable.
export function MyComponent() {
const {
data: myData,
status,
error,
} = tables.folders.useLoadData(
// custom query function returns a promise for retrieving the data
async () => {
const { data } = await getData<MyDataType[]>('/mydata/endpoint', 'GET');
return data;
},
{
refreshOn: [],
refreshMode: 'append',
fetchOnMount: !singles.dataLoaded.get(),
onSuccess: () => singles.dataLoaded.set(true),
filter: (row) => row.value > 10,
}
);
if (status === 'loading') {
return <div>Loading</div>;
}
if (error) {
return <div>{error}</div>;
}
return (
<ul>
{myData.map(d => <li key={d.key}>{d.value}</li>)}
</ul>
);
}
Retrieves matching rows from the specified table without causing your component to rerender.
find(where?: Partial<T> | ((v: TableRow<T>) => boolean)): TableRow<T>[]
- where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean
): receives an object to match rows based on equality of each property value, or a function that returns true if the row should be returned and false if it should not be returned. If omitted, all rows will be returned from the table.
// return all rows from the cats table
import { tables } from './store';
const rows = tables.cats.find();
// return all rows from the cats table named "PJ"
import { tables } from './store';
const rows = tables.cats.find({ name: "PJ" });
// return all rows from the cats table with an age greater than 7
import { tables } from './store';
const rows = tables.cats.find(cat => cat.age > 7);
Retrieves the first matching row from the specified table without causing your component to rerender.
findOne(where?: Partial<T> | ((v: TableRow<T>) => boolean)): TableRow<T> | undefined
- where (optional) (
Partial<T> | ((v: TableRow<T>) => boolean)
): receives an object to match rows based on equality of each property value, or a function that returns true if the row should be returned and false if it should not be returned.
// returns the first row where the name is "PJ"
import { tables } from './store';
const row = tables.cats.findOne({ name: 'PJ' })
// returns the first row where the age is greater than 7
import { tables } from './store';
const row = tables.cats.findOne(cat => cat.age > 7)
Retrieves the row matching the provided _id from the specified table without causing your component to rerender.
findById(_id: number): TableRow<T> | undefined
- _id (
number
): the _id of the row to return.
// returns the row with a _id of 10
import { tables } from './store';
const row = tables.cats.findById(10);
Retrieves each row in the table one at a time without causing your component to rerender
scan(fn: (row: TableRow<T>, i: number) => boolean | void): void
- fn (
(row: TableRow<T>, idx: number) => boolean | void
): a function that receives the next row in the table and zero-based row counter. Return false if scanning should stop early.
// return the first three rows in the table
import { tables } from './store';
const rows = [];
tables.cats.scan((cat, i) => {
if (i == 3) {
return false;
}
rows.push(cat);
});
Returns the number of matching rows in the specified.
count(where?: Partial<T> | ((v: TableRow<T>) => boolean)): number
- where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean
): receives an object to count rows based on equality of each property value, or a function that returns true if the row should be counted and false if it should not be counted. If omitted, all rows will be counted from the table.
// count all rows from the cats table
import { tables } from './store';
const n = tables.cats.count();
// count all rows from the cats table named "PJ"
import { tables } from './store';
const n = tables.cats.count({ name: "PJ" });
// count all rows from the cats table with an age greater than 7
import { tables } from './store';
const n = tables.cats.count(cat => cat.age > 7);
Inserts a new row into the specified table. The user does not need to provide the _id property as this will be handled automatically. This will return the newly inserted row or undefined if the user has a beforeInsertTrigger attached to the table that aborts the insert.
insertOne(row: T): TableRow<T> | undefined
- row (
object
): an object with keys and values for the table's column names
// returns the newly insertedRow
import { tables } from './store';
const row = tables.cats.insertOne({ name: 'Cleo', age: 7 });
Inserts multiple rows into the specified table. The user does not need to provide the _id property for each row as this will be handled automatically. This will return the newly inserted rows. Any attached triggers (e.g., beforeInsertTrigger) will be fired for each row. By default, components with a matching use() hook will only be rerendered after all rows are inserted. To override this behavior, pass false as the second argument, instructing Trigger to rerender components on each insert, which is the same behavior as manually calling insertRow() multiple times.
insertMany(rows: T[], batchNotify?: boolean): TableRow<T>[]
- rows (
object[]
): an array of objects with keys and values for the table's column names - batchNotify (optional) (
boolean
): passing false will rerender components for each inserted row
// returns the newly inserted rows; components will rerender after all rows are inserted
import { tables } from './store';
const rows = tables.cats.insertMany([ { name: 'Cleo', age: 7 }, { name: 'PJ', age: 6 } ]);
// returns the newly inserted rows; components will rerender as each row is inserted
import { tables } from './store';
const rows = tables.cats.insertMany([ { name: 'Cleo', age: 7 }, { name: 'PJ', age: 6 } ], false);
A trigger function that can be attached to a table before a new row is inserted.
onBeforeInsert(fn: (row: TableRow<T>) => TableRow<T> | void | boolean): void
- fn (
(row: TableRow<T>) => TableRow<T> | void | boolean
): a function that receives the row being inserted, allowing changes to be made to the value prior to insertion. The user can cancel the insert by returning false. Returning nothing or true will ignore any changes made in the function and insert the row as originally intended.
// when inserting a row, change all names to lowercase and add 1 to the age
import { tables } from './store';
tables.cats.onBeforeInsert(cat => {
cat.name = cat.name.toLowerCase();
cat.age += 1;
return cat;
});
A trigger function that can be attached to a table after a new row is inserted.
onAfterInsert(fn: (row: TableRow<T>) => void): void
- fn (
(row: TableRow<T>) => void
): a function that receives the row that was just inserted. This can be useful when needing to perform additional actions (e.g., inserting a row into another table) based on the value of the inserted row.
// the newly insert row is used to insert a row into another table
import { tables } from './store';
tables.cats.onAfterInsert(cat => {
tables.coolCats.insertOne({ name: cat.name, age: cat.age });
});
Will delete the first matching row only, returning true if a row was deleted and false if a row was not deleted. The primary use of this function is for when the user knows the _id of the row to be deleted.
deleteOne(Partial<T> | ((row: TableRow<T>) => boolean)): boolean
- where (
(Partial<T> | ((row: TableRow<T>) => boolean)
): a function that receives the _id of the row to delete, an object to match the first row found based on equality of each property value, or a function that returns true if the row should be deleted and false if it should not be deleted
// delete the first cat found with the name "PJ"
import { tables } from './store';
tables.cats.deleteOne({ name: 'PJ' });
// delete the first cat found whose age is > 7
import { tables } from './store';
tables.cats.deleteOne(cat => cat.age > 7);
Will delete the row matching the provided _id, returning true if a row was deleted and false if a row was not deleted. The primary use of this function is for when the user knows the _id of the row to be deleted.
deleteById(_id: number): boolean
- _id (
number
): the _id of the row to delete.
// delete the cat with a _id entry of 3
import { tables } from './store';
tables.cats.deleteById(3);
Will delete all rows matching the object or function passed to the where parameter. If where is undefined or null, all rows in the table will be deleted.
deleteMany(where?: Partial<T> | ((row: TableRow<T>) => boolean) | null, batchNotify?: boolean): number
- where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean
): an object to match rows based on equality of each property value, or a function that returns true if the row should be deleted and false if it should not be deleted. Any attached triggers (e.g., onDelete) will be fired for each row. By default, components with a matching use() hook will only be rerendered after all rows are deleted (batch). To override this behavior, pass false as the second argument, instructing Trigger to rerender components on each delete, which is the same behavior as manually calling deleteRow() multiple times. Components with a matching useById() hook will be rerendered immediately if the row they are subscribed to is deleted. If undefined or null, all rows in the table will be deleted. - batchNotify (optional) (
boolean
): passing false will rerender components for each deleted row
// delete all rows from the coolcats table
import { tables } from './store';
tables.coolcats.deleteMany();
// delete all rows from the cats table named "PJ" and are 7 years old
import { tables } from './store';
tables.cats.deleteMany({ name: "PJ", age: 7 });
// delete all rows from the cats table with an age greater than 7
import { tables } from './store';
tables.cats.deleteMany(cat => cat.age > 7);
A trigger function that can be attached to a table before a row is deleted.
onBeforeDelete(fn: (row: TableRow<T>) => boolean | void): void
- fn (
(row: TableRow<T>) => boolean | void
): a function that receives the row being deleted. The user can cancel the deletion by returning false. Returning nothing or true will delete the row as originally intended.
// prevent deletion of cats named "Cleo"
import { tables } from './store';
tables.cats.onBeforeDelete(cat => {
if (cat.name === "Cleo") {
return false // prevent deletion
}
)};
A trigger function that can be attached to a table after a row is deleted.
onAfterDelete(fn: (row: TableRow<T>) => void): void
- fn (
(row: TableRow<T>) => void
): a function that receives the row that was just deleted. This can be useful when needing to perform additional actions (e.g., deleting a row from another table) based on the value of the deleted row.
// the deleted row is used to delete a row from another table
import { tables } from './store';
tables.cats.onAfterDelete(cat => {
tables.coolCats.deleteRow({ name: cat.name });
});
Update an existing row in the specified table. The user needs to know the _id of the row to be updated.
updateById(_id: number, setValue: Partial<T> | ((row: TableRow<T>) => Partial<T>), render?: boolean): TableRow<T> | undefined
- _id (
number
): the _id of the row to update. - setValue (
Partial<T> | ((row: TableRow<T>) => Partial<T>)
): an object with values for each property to update, or a function that receives the row and returns an object with values for each property to update. - render (optional) (
boolean
): default value is true. Passing false will update the data but not cause a rerender for any components
// change the name of the cat with _id entry of 10 to "Pickles"
import { tables } from './store';
const row = tables.cats.updateById(10, { name: 'Pickles' });
// increment the age of the cat with _id entry of 10
import { tables } from './store';
const row = tables.cats.updateById(10, cat => ({ age: cat.age++ }));
A function that will update all rows matching the object or function passed to the where parameter. If where is undefined or null, all rows in the table will be updated.
updateMany(setValue: Partial<T> | ((row: TableRow<T>) => Partial<T>), where?: Partial<T> | ((row: TableRow<T>) => boolean) | null, options?: object): TableRow<T>[]
- setValue (
Partial<T> | ((row: TableRow<T>) => Partial<T>)
): an object with values for each property to update, or a function that receives the row and returns an object with values for each property to update. - where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean | null
): an object to match rows based on equality of each property value, or a function that returns true if the row should be updated and false if it should not be updated. Any attached triggers (e.g., onDelete) will be fired for each row. If undefined or null, all rows in the table will be updated. - options (optional) (
object
):- render (optional) (
boolean
): default value is true. To override this behavior, pass false, instructing Trigger to update the values, but not rerender components. - batchNotify (optional) (
boolean
): default value is true. Unless, render is set to false, components with a matching useById() hook will be rerendered after reach row is updated. Components with a matching use() hook will be rerendered after all rows are updated (batch). To override this behavior, pass false, instructing Trigger to rerender all components on each row update, which is the same behavior as manually calling updateRow() multiple times. Components with a matching useById() hook will be rerendered immediately if the row they are subscribed to is updated regardless of whether batchNotify is set to true or false.
- render (optional) (
// update all cats to be named "PJ"
import { tables } from './store';
tables.cats.updateMany({ name: "PJ" });
// increment the age of all cats who are named "PJ"
import { tables } from './store';
tables.cats.updateMany(cat => ({ age: cat.age++ }), { name: "PJ" });
// change the name of all cats named "PJ" and older than 7 to "Old PJ"; components will rerender as each row is updated
import { tables } from './store';
tables.cats.updateMany({ name: "Old PJ" }, cat => cat.age > 7 && cat.name == "PJ", false);
A trigger function that can be attached to a table before a row is updated.
onBeforeUpdate(fn: (currentValue: TableRow<T>, newValue: TableRow<T>) => TableRow<T> | void | boolean): void
- fn (
(currentValue: TableRow<T>, newValue: TableRow<T>) => TableRow<T> | void | boolean
): a function that receives the row's current value and the new value, allowing changes to be made to the value prior to updating. The user can cancel the update by returning false. Returning nothing or true will update the row as originally intended.
// prevent updates to cats named "Cleo"
import { tables } from './store';
tables.cats.onBeforeUpdate(cat => {
if (cat.name === "Cleo") {
return false // prevent updating
}
)};
A trigger function that can be attached to a table after a row is updated.
onAfterUpdate(fn: (previousValue: TableRow<T>, newValue: TableRow<T>) => void): void
- fn (
(previousValue: TableRow<T>, newValue: TableRow<T>) => void
): a function that receives the row's previous value and the row's new value. This can be useful when needing to perform additional actions (e.g., comparing changes or updating a row from another table) based on the value of the updated row.
// the updated row is used to update a row from another table
import { tables } from './store';
tables.cats.onAfterUpdate((previousValue, newValue) => {
if (newValue.age > previousValue.age) {
tables.cats.updateRow(newValue._id, { name: "Old Cat" });
}
});
Returns the column names for the specified table (including the _id column)
columnNames(): (keyof TableRow<T>)[]
// get column names for the cats table
import { tables } from './store';
const columns = tables.cats.columnNames();
Prints the specified table to the console to view its contents. Some browsers require the developer console to be open for the table to print; otherwise, an object will be logged instead. You can copy this object and manually type console.table(
print(where?: Partial<T> | ((row: TableRow<T>) => boolean) | null, n?: number): void
- where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean
): receives an object to match rows based on equality of each property value, or a function that returns true if the row should be printed and false if it should not be printed. If omitted, all rows will be returned from the table. - n (optional) (
number
): the number of rows to be printed (defaults to 50). Passing -1 will print all rows based on browser limitations.
// print the first 50 rows from the cats table to the console
import { tables } from './store';
tables.cats.print();
// print the first 100 rows from the cats table to the console
import { tables } from './store';
tables.cats.print(null, 100);
// print all rows from the cats table to the console where the age is greater than 7
import { tables } from './store';
tables.cats.print(cat => cat.age > 7, -1);
// print the first 50 rows from the cats table to the console where the name is "PJ"
import { tables } from './store';
tables.cats.print({ name: "PJ" });
Returns rows from specified table as a JSON string.
toJSON(index?: boolean, where?: Partial<T> | ((row: TableRow<T>) => boolean) | null, n?: number): string
- index (optional) (
boolean
): determines if the _id for each row should be included (defaults to false) - where (optional) (
Partial<T> | ((row: TableRow<T>) => boolean
): receives an object to match rows based on equality of each property value, or a function that returns true if the row should be returned and false if it should not be returned. If omitted, all rows will be returned from the table. - n (optional) (
number
): the number of rows to be returned (defaults to 50). Passing -1 will return all rows based on browser limitations.
// return the first 50 rows from the cats table as a JSON string, and omit the _id
import { tables } from './store';
const jsonString = tables.cats.toJSON();
// return the first 100 rows from the cats table as a JSON string, and omit the _id
import { tables } from './store';
const jsonString = tables.cats.toJSON(false, null, 100);
// return all rows from the cats table as a JSON string where the age is greater than 7, and include the _id
import { tables } from './store';
const jsonString = tables.cats.toJSON(true, cat => cat.age > 7, -1);
// return the first 50 rows from the cats table as a JSON string where the name is "PJ", and omit the _id
import { tables } from './store';
const jsonString = tables.cats.toJSON(false, { name: "PJ" });