Adding Data
Fast and responsive user experience using optimistic updates.
Why Use Mutations
You need to create new records or update existing ones in your database. The Squid Client SDK provides insert and update operations that apply changes optimistically on the client for instant UI feedback, then sync with the server asynchronously.
Quick Start
// Insert a new document
await squid.collection<User>('users').doc('user_1').insert({
name: 'Alice',
email: 'alice@example.com',
});
Overview
Unless being run in a transaction, all inserts and updates return a Promise which resolves once the mutation is applied on the server.
Inserts and updates are applied optimistically locally and reflect immediately on the client. The changes are then sent to the server asynchronously to ensure a consistent, clean data state.
There are three types of write mutations: insert, update, and setInPath. Each is performed on a document reference.
Core Concepts
Insert
Insert is used for creating a new document.
To insert a new document into a collection, call the insert method on a DocumentReference and pass in the
new document data as an argument:
try {
await squid.collection<User>('users').doc('new_user_id').insert({
name: 'John Doe',
email: 'johndoe@example.com',
});
console.log('User added successfully');
} catch (error) {
console.error(`Failed to add user ${error}`);
}
The backend security rules enable you to control who can perform each mutation in a granular way. These rules receive
a MutationContext as a parameter, which contains all the needed details about the mutation including the snapshot of
the document before and after the change. Read more about security rules to
understand how to write them.
Insert many
The insertMany method is used for efficiently inserting and/or updating multiple documents at once. The following example adds an array of new user documents:
const newDocuments = [
{
id: 'new_user_id1',
data: {
name: 'John Doe',
email: 'johndoe@example.com',
},
},
{
id: 'new_user_id2',
data: {
name: 'Jan Smith',
email: 'jansmith@example.com',
},
},
];
try {
await squid.collection<User>('users').insertMany(newDocuments);
console.log('Users added successfully');
} catch (error) {
console.error(`Failed to add users ${error}`);
}
Update
To update a document, call the update method on a DocumentReference and pass in an object that contains the
partial update data as an argument:
try {
await squid
.collection<User>('users')
.doc('existing_user_id')
.update({ email: 'new_email@example.com' });
console.log('User updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
Set in Path
You can also update a specific property of a document by calling the setInPath method on a DocumentReference and
passing the path to the property and the new value as arguments. Use dot notation to specify nested properties in the path:
const userRef = squid.collection<User>('users').doc('existing_user_id');
try {
await userRef.setInPath('address.street', 'Main');
console.log('Updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Security rule rejection | The mutation was blocked by security rules | Verify the user has write permission for the collection |
| Document already exists | Calling insert on a document ID that already exists in some connector types | Use update for existing documents, or use a unique ID |
| Invalid data shape | The inserted data does not match the collection schema | Ensure the data object matches the expected schema and types |
| Network error | The server could not be reached to confirm the mutation | The optimistic update is rolled back; retry the operation |
Best Practices
-
Use
update()for partial changes to send only the fields that changed, rather than re-inserting the entire document. -
Use
setInPath()for deeply nested updates to modify a single nested field without touching the rest of the document:Client code// Update only the city without affecting other address fields
await userRef.setInPath('address.city', 'New York'); -
Use
insertMany()for bulk operations to reduce the number of round trips to the server. -
Wrap related mutations in a transaction when you need atomicity across multiple documents.
-
Handle errors on mutations since the server may reject changes that pass client-side validation but fail security rules or schema checks.