Page updated Jan 16, 2024

Set up Amplify DataStore

DataStore with Amplify

Amplify DataStore provides a programming model for leveraging shared and distributed data without writing additional code for offline and online scenarios, which makes working with distributed, cross-user data just as simple as working with local-only data.

Note: this allows you to start persisting data locally to your device with DataStore, even without an AWS account.

Goal

To setup and configure your application with Amplify DataStore and use it to persist data locally on a device.

Prerequisites

  • Install Amplify CLI version 12.5.1 or later by running:
npm install -g @aws-amplify/cli
1npm install -g @aws-amplify/cli
curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
1curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd
1curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd

Setup local development environment

To get started, first create a new React app with vite using the following commands:

npm create vite@latest ✔ Project name: amplify-datastore ✔ Select a framework: › React ✔ Select a variant: › JavaScript cd amplify-datastore
1npm create vite@latest
2✔ Project name: amplify-datastore
3✔ Select a framework: › React
4✔ Select a variant: › JavaScript
5
6cd amplify-datastore

To use Amplify, you must first initialize it for use in your project. If you haven't already done so, run this command:

amplify init
1amplify init

The base structure for a DataStore app is created by adding a new GraphQL API to your app.

# For new APIs amplify add api # For existing APIs amplify update api
1# For new APIs
2amplify add api
3
4# For existing APIs
5amplify update api

The CLI will prompt you to configure your API. Select GraphQL as the API type and reply to the questions as shown below. Conflict detection is required when using DataStore to sync data with the cloud.

? Please select from one of the below mentioned services: `GraphQL` ? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Name` ? Provide API name: `BlogAppApi` ? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Authorization modes: API key (default, expiration time: 7 days from now)` ? Choose the default authorization type for the API `API key` ? Enter a description for the API key: `BlogAPIKey` ? After how many days from now the API key should expire (1-365): `365` ? Configure additional auth types? `No` ? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Conflict detection (required for DataStore): Disabled` ? Enable conflict detection? `Yes` ? Select the default resolution strategy `Auto Merge` ? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Continue` ? Choose a schema template `Single object with fields (e.g., “Todo” with ID, name, description)`
1? Please select from one of the below mentioned services:
2 `GraphQL`
3? Here is the GraphQL API that we will create. Select a setting to edit or continue:
4 `Name`
5? Provide API name:
6 `BlogAppApi`
7? Here is the GraphQL API that we will create. Select a setting to edit or continue:
8 `Authorization modes: API key (default, expiration time: 7 days from now)`
9? Choose the default authorization type for the API
10 `API key`
11? Enter a description for the API key:
12 `BlogAPIKey`
13? After how many days from now the API key should expire (1-365):
14 `365`
15? Configure additional auth types?
16 `No`
17? Here is the GraphQL API that we will create. Select a setting to edit or continue:
18 `Conflict detection (required for DataStore): Disabled`
19? Enable conflict detection?
20 `Yes`
21? Select the default resolution strategy
22 `Auto Merge`
23? Here is the GraphQL API that we will create. Select a setting to edit or continue:
24 `Continue`
25? Choose a schema template
26 `Single object with fields (e.g., “Todo” with ID, name, description)`

Troubleshooting: Cloud sync will fail without the conflict detection configuration. To enable it for an existing project, run amplify update api and choose Enable conflict detection (required for DataStore).

Next, install the Amplify library dependencies in your project by running:

npm install aws-amplify
1npm install aws-amplify

Idiomatic persistence

DataStore relies on platform standard data structures to represent the data schema in an idiomatic way. The persistence language is composed by data types that satisfies the Model interface and operations defined by common verbs such as save, query and delete.

Data schema

The first step to create an app backed by a persistent datastore is to define a schema. DataStore uses GraphQL schema files as the definition of the application data model. The schema contains data types and relationships that represent the app's functionality.

Sample schema

For the next steps, let's start with a schema for a small blog application. Currently, it has only a single model. New types and constructs will be added to this base schema as more concepts are presented.

Open the schema.graphql file located by default at amplify/backend/{api_name}/ and define a model Post as follows.

type Post @model { id: ID! title: String! status: PostStatus! rating: Int content: String } enum PostStatus { ACTIVE INACTIVE }
1type Post @model {
2 id: ID!
3 title: String!
4 status: PostStatus!
5 rating: Int
6 content: String
7}
8
9enum PostStatus {
10 ACTIVE
11 INACTIVE
12}

Now you will to convert the platform-agnostic schema.graphql into platform-specific data structures. DataStore relies on code generation to guarantee schemas are correctly converted to platform code.

Like the initial setup, models can be generated either using the IDE integration or Amplify CLI directly.

Code generation: Platform integration

When using npx amplify-app, an NPM script named amplify-modelgen should be added to your package.json. You can generate model code with the following command.

npm run amplify-modelgen
1npm run amplify-modelgen

The following files will be generated.

src/ |_ models/ |_ index.d.ts |_ index.js |_ schema.d.ts |_ schema.js
1src/
2|_ models/
3 |_ index.d.ts
4 |_ index.js
5 |_ schema.d.ts
6 |_ schema.js

The .d.ts are TypeScript declaration files. If your project does not use TypeScript, do not worry, those files can still provide most editors a better developer experience, with a more accurate auto-complete and realtime type checking. Worst case scenario they will just be ignored.

Code generation: Amplify CLI

Models can also be generated using the Amplify CLI directly.

In your terminal, make sure you are in your project/root folder and execute the codegen command:

amplify codegen models
1amplify codegen models

You can find the generated files at amplify/generated/models/.

Initialize Amplify DataStore

When the aws-amplify/datastore dependency is added to the project, the plugin is automatically initialized when you start using it.

Persistence operations

Now the application is ready to execute persistence operations. The data will be persisted to a local database, enabling offline-first use cases by default.

Even though a GraphQL API is already added to your project, the cloud synchronization will only be enabled when the API plugin is initialized and the backend provisioned. See the Next steps for more info.

Writing to the database

To write to the database, create an instance of the Post model and save it.

try { const post = await DataStore.save( new Post({ title: 'My First Post' }) ); console.log('Post saved successfully!', post); } catch (error) { console.log('Error saving post', error); }
1try {
2 const post = await DataStore.save(
3 new Post({
4 title: 'My First Post'
5 })
6 );
7 console.log('Post saved successfully!', post);
8} catch (error) {
9 console.log('Error saving post', error);
10}

Reading from the database

To read from the database, the simplest approach is to query for all records of a given model type.

try { const posts = await DataStore.query(Post); console.log('Posts retrieved successfully!', JSON.stringify(posts, null, 2)); } catch (error) { console.log('Error retrieving posts', error); }
1try {
2 const posts = await DataStore.query(Post);
3 console.log('Posts retrieved successfully!', JSON.stringify(posts, null, 2));
4} catch (error) {
5 console.log('Error retrieving posts', error);
6}

Next steps

Congratulations! You’ve created and retrieved data from the local database. Check out the following links to see other Amplify DataStore use cases and advanced concepts: