Skip to content

Latest commit

 

History

History
105 lines (86 loc) · 2.37 KB

CodeSnippets.md

File metadata and controls

105 lines (86 loc) · 2.37 KB

Code Snippets for Data Store

Table of Contents

Storing data

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)
  }

Query Data

Case 1 -

To fetch all the data from data model

async function fetchComments(){
    const comment = await DataStore.query(Comment);
}

Case 2 -

To fetch single data from data model

async function fetchComments(id){
    const comment = await DataStore.query(Comment, id);
    console.log(comment);
}

Case 3 -

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);
  }

Case 4 -

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);
}

Real Time data

To display real-time data

  useEffect(() => {
    const subscription = DataStore.observe(Comment).subscribe((msg) => {
      fetchComments();
    });

    return () => subscription.unsubscribe();
  }, []);

Delete Data

To delete the particular data item from Data model

 async function handleDelete(id) {

    const todelete = await DataStore.query(Comment, id);
    DataStore.delete(todelete);
  }

Reference

https://docs.amplify.aws/lib/datastore/getting-started/q/platform/js