Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Example application

/**
* React Native DataStore Sample App
*/
import React, { Component } from 'react';
import { Text, StyleSheet, ScrollView } from 'react-native';
import { Amplify } from 'aws-amplify';
import { DataStore, Predicates } from 'aws-amplify/datastore';
import { Post, PostStatus, Comment } from './src/models';
import amplifyconfig from './amplifyconfiguration.json';
Amplify.configure(amplifyconfig);
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() {
DataStore.save(
new Post({
title: `New Post ${Date.now()}`,
rating: Math.floor(Math.random() * (8 - 1) + 1),
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;

API Reference

For the complete API documentation for DataStore, visit our API Reference