React Native – How to use AWS DataStore for local storage (1)?

Install dependencies

$ npx amplify-app@latest
$ yarn add @aws-amplify/core @aws-amplify/datastore
$ yarn add @react-native-community/netinfo
$ cd ios && pod install && cd ..

Setup React Native app

Setup “amplify/backend/api/amplifyDatasource/schema.graphql”

enum PostStatus {
  ACTIVE
  INACTIVE
}

type Post @model {
  id: ID!
  title: String!
  comments: [Comment] @connection(name: "PostComments")
  rating: Int!
  status: PostStatus!
}

type Comment @model {
  id: ID!
  content: String
  post: Post @connection(name: "PostComments")
}

Create Amplify app

  • Delete “.config/project-config.json” to create new app
  • Run “$ amplify init

Add backend API for Amplify app

$ amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: datastore
? Choose the default authorization type for the API API key
? Enter a description for the API key: testing
? After how many days from now the API key should expire (1-365): 365
? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Do you want a guided schema creation? Yes
? What best describes your project: One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
? Do you want to edit the schema now? Yes
Please edit the file in your editor: /Volumes/Data/react-native-aws-amplify-datastore/amplify/backend/api/datastore/schema.graphql
  • Open “amplify/backend/api/AmplifyDatastore/schema.graphql”
  • Copy paste content of “amplify/backend/api/amplifyDatasource/schema.graphql” to this one
? Press enter to continue

Push to cloud

$ amplify push
Edit your schema at /Volumes/Data/react-native-aws-amplify-datastore/amplify/backend/api/datastore/schema.graphql or place .graphql files in a directory at /Volumes/Data/react-native-aws-amplify-datastore/amplify/backend/api/datastore/schema
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2

Build React Native app dealing with local data

Generate models

yarn amplify-modelgen

If no model is created, check “amplify/.config/local-env-info.json” to see “projectPath” is correct or not

Coding

/**
 * React Native DataStore Sample App
 */

import React, {Component} from 'react';
import {Text, StyleSheet, ScrollView} from 'react-native';

import Amplify from '@aws-amplify/core';
import {DataStore, Predicates} from '@aws-amplify/datastore';
import {Post, PostStatus, Comment} from './src/models';

import awsConfig from './aws-exports';
Amplify.configure(awsConfig);
let subscription;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    };
  }

  componentDidMount() {
    this.onQuery();
    subscription = DataStore.observe(Post).subscribe(msg => {
      console.log('SUBSCRIPTION_UPDATE', msg);
      this.onQuery();
    });
  }

  componentWillUnmount() {
    subscription.unsubscribe();
  }

  onCreatePost() {
    // Data is persisted in offline storage
    DataStore.save(
      new Post({
        title: `New Post ${Date.now()}`,
        rating: (function getRandomInt(min, max) {
          min = Math.ceil(min);
          max = Math.floor(max);
          return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
        })(5, 10),
        status: PostStatus.ACTIVE,
      }),
    );
  }

  async onCreatePostAndComments() {
    const post = new Post({
      title: `New Post with comments ${Date.now()}`,
      rating: 5,
      status: PostStatus.ACTIVE,
    });

    await DataStore.save(post);

    for (let i = 0; i < 2; i++) {
      DataStore.save(
        new Comment({
          content: `New comment ${Date.now()}`,
          post,
        }),
      );
    }
  }

  onQuery = async () => {
    const posts = await DataStore.query(Post, c => c.rating('gt', 2));
    console.log('QUERY_POSTS_RESULT', posts);
    const comments = await DataStore.query(Comment);
    this.setState({posts});
    console.log('QUERY_COMMENTS_RESULT', comments);
  };

  onDelete = async () => {
    const deletedPosts = await DataStore.delete(Post, Predicates.ALL);
    console.log('DELETE_RESULT', deletedPosts);
  };

  render() {
    return (
      <ScrollView
        style={styles.scrollview}
        contentContainerStyle={styles.container}>
        <Text style={styles.text} onPress={this.onCreatePost}>
          Create Post
        </Text>
        <Text style={styles.text} onPress={this.onCreatePostAndComments}>
          Create Post & Comments
        </Text>
        <Text style={styles.text} onPress={this.onQuery}>
          Query Posts
        </Text>
        <Text style={styles.text} onPress={this.onDelete}>
          Delete All Posts
        </Text>
        {this.state.posts.map((post, i) => (
          <Text key={i}>{`${post.title} ${post.rating}`}</Text>
        ))}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  scrollview: {
    paddingTop: 40,
    flex: 1,
  },
  container: {
    alignItems: 'center',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

export default App;

git reference: react-native-aws-amplify-datastore

Error

Check “amplify/.config/local-env-info.json” to make sure “projectPath” correct

Be the first to comment

Leave a Reply

Your email address will not be published.


*