Example application
1/**2 * React Native DataStore Sample App3 */4
5import React, { Component } from 'react';6import { Text, StyleSheet, ScrollView } from 'react-native';7
8import { Amplify } from 'aws-amplify';9import { DataStore, Predicates } from 'aws-amplify/datastore';10import { Post, PostStatus, Comment } from './src/models';11
12import amplifyconfig from './amplifyconfiguration.json';13Amplify.configure(amplifyconfig);14let subscription;15
16class App extends Component {17 constructor(props) {18 super(props);19 this.state = {20 posts: []21 };22 }23
24 componentDidMount() {25 this.onQuery();26 subscription = DataStore.observe(Post).subscribe((msg) => {27 console.log('SUBSCRIPTION_UPDATE', msg);28 this.onQuery();29 });30 }31
32 componentWillUnmount() {33 subscription.unsubscribe();34 }35
36 onCreatePost() {37 DataStore.save(38 new Post({39 title: `New Post ${Date.now()}`,40 rating: Math.floor(Math.random() * (8 - 1) + 1),41 status: PostStatus.ACTIVE42 })43 );44 }45
46 async onCreatePostAndComments() {47 const post = new Post({48 title: `New Post with comments ${Date.now()}`,49 rating: 5,50 status: PostStatus.ACTIVE51 });52
53 await DataStore.save(post);54
55 for (let i = 0; i < 2; i++) {56 DataStore.save(57 new Comment({58 content: `New comment ${Date.now()}`,59 post60 })61 );62 }63 }64
65 onQuery = async () => {66 const posts = await DataStore.query(Post, (c) => c.rating.gt(2));67 console.log('QUERY_POSTS_RESULT', posts);68 const comments = await DataStore.query(Comment);69 this.setState({ posts });70 console.log('QUERY_COMMENTS_RESULT', comments);71 };72
73 onDelete = async () => {74 const deletedPosts = await DataStore.delete(Post, Predicates.ALL);75 console.log('DELETE_RESULT', deletedPosts);76 };77
78 render() {79 return (80 <ScrollView81 style={styles.scrollview}82 contentContainerStyle={styles.container}83 >84 <Text style={styles.text} onPress={this.onCreatePost}>85 Create Post86 </Text>87 <Text style={styles.text} onPress={this.onCreatePostAndComments}>88 Create Post & Comments89 </Text>90 <Text style={styles.text} onPress={this.onQuery}>91 Query Posts92 </Text>93 <Text style={styles.text} onPress={this.onDelete}>94 Delete All Posts95 </Text>96 {this.state.posts.map((post, i) => (97 <Text key={i}>{`${post.title} ${post.rating}`}</Text>98 ))}99 </ScrollView>100 );101 }102}103
104const styles = StyleSheet.create({105 scrollview: {106 paddingTop: 40,107 flex: 1108 },109 container: {110 alignItems: 'center'111 },112 text: {113 fontSize: 20,114 textAlign: 'center',115 margin: 10116 }117});118
119export default App;
API Reference
For the complete API documentation for DataStore, visit our API Reference