Create, update, and delete application data
In this guide, you will learn how to create, update, and delete your data using Amplify Libraries' Data client.
Before you begin, you will need:
Create an item
You can create an item by first generating the Data client with your backend Data schema. Then you can add an item:
1import { generateClient } from 'aws-amplify/data';2import { type Schema } from '@/amplify/data/resource'3
4const client = generateClient<Schema>();5
6const { errors, data: newTodo } = await client.models.Todo.create({7 content: "My new todo",8 done: true,9})
Update an item
To update the item, use the update
function:
1import { generateClient } from 'aws-amplify/data';2import { type Schema } from '@/amplify/data/resource'3
4const client = generateClient<Schema>();5
6const todoDetails = {7 id: 'some_id',8 description: 'Updated description'9};10
11const { data: updatedTodo, errors } = await client.models.Todo.update(todo)
Delete an item
You can then delete the Todo by using the delete mutation. To specify which item to delete, you only need to provide the id
of that item:
1import { generateClient } from 'aws-amplify/data';2import { type Schema } from '@/amplify/data/resource'3
4const client = generateClient<Schema>();5
6const toBeDeletedTodo = {7 id: "123123213"8}9
10const { data: deletedTodo, errors } = await client.models.Todo.delete(toBeDeletedTodo)
Cancel create, update, and delete requests
You can cancel any mutation API request by calling .cancel
on the mutation request promise that's returned by .create(...)
, .update(...)
, or .delete(...)
.
1const promise = client.models.Todo.create({ content: "New Todo "})2 // ^ Note: we're not awaiting the request, we're returning the promise3
4try {5 await promise;6} catch (error) {7 console.log(error);8 // If the error is because the request was cancelled you can confirm here.9 if (client.isCancelError(error)) {10 console.log(error.message); // "my message for cancellation"11 // handle user cancellation logic12 }13}14
15...16
17// To cancel the above request18client.cancel(promise, "my message for cancellation");
You need to ensure that the promise returned from .create()
, .update()
, and .delete()
has not been modified. Typically, async functions wrap the promise being returned into another promise. For example, the following will not work:
1async function makeAPICall() {2 return client.models.Todo.create({ content: 'New Todo' });3}4const promise = makeAPICall();5
6// The following will NOT cancel the request.7client.cancel(promise, 'my error message');
Conclusion
Congratulations! You have finished the Create, update, and delete application data guide. In this guide, you created, updated, and deleted your app data.
Next steps
Our recommended next steps include using the API to query data and subscribe to real-time events to look for mutations in your data. Some resources that will help with this work include: