To save data in the data model
async function handleSubmit(e){
e.preventDefault();
await DataStore.save(
new Comment({
"postID": postID, // postID received as props
"createdBy": createdBy, //
"content": comment,
"createdAt":new Date().toLocaleString()
})
);
console.log(comment, postID, createdBy)
}
To fetch all the data from data model
async function fetchComments(){
const comment = await DataStore.query(Comment);
}
To fetch single data from data model
async function fetchComments(id){
const comment = await DataStore.query(Comment, id);
console.log(comment);
}
To fetch filtered data from data model
async function fetchComments() {
const comment = (await DataStore.query(Comment)).filter(
(c) => c.postID === postID //postID received as props
);
setDisplayComments(comment);
}
To fetch and display data in particular sorted order
async function fetchComments() {
const comments = await DataStore.query(Comment, Predicates.ALL, {
sort: (s) => s.createdAt(SortDirection.DESCENDING)
});
/* const posts = await DataStore.query(Comment, Predicates.ALL, {
sort: (s) => s.createdAt(SortDirection.ASCENDING)
}); */
console.log(comments);
setDisplayComments(comments);
}
To display real-time data
useEffect(() => {
const subscription = DataStore.observe(Comment).subscribe((msg) => {
fetchComments();
});
return () => subscription.unsubscribe();
}, []);
To delete the particular data item from Data model
async function handleDelete(id) {
const todelete = await DataStore.query(Comment, id);
DataStore.delete(todelete);
}
https://docs.amplify.aws/lib/datastore/getting-started/q/platform/js