Checking status of amplify datastore operation

420 views Asked by At

How can I check whether the operation is successful? I only see warnings and try/catch doesn't seem to work.

let post = await DataStore.save(
  new Post(postData)
);

enter image description here

1

There are 1 answers

0
julie On

DataStore operations such as save, create, query return a promise. That is what you are waiting for with await in your question. You are waiting for the promise to resolve. With your use, if the promise resolves successfully then post has the new value. If the promise resolves unsuccessfully then the post variable will not have a valid post as a value.

You can use promises to provide callbacks for success and error by using then and catch. The callbacks are aynchronous so your code execution will not wait for completion but will continue and the callbacks will handle the completion of the DataStore operation at some time in the future when the promise resolves.

Assuming that you postData is an object postData = {field1: 'value', field2: 'another value'} Then you can pass it as you did, or use the spread operator "..." to merge it with default fields and then pass the new object to the Post constructor. Below is an example with some default fields added just to show more advanced use.

  const postDefaults = { field3: 63, field4: 'a value' }
  const postData = { field1: 'value', postDate: Date.now() }

  DataStore.save(new Post({...postDefaults, ...postData}))
    .then((post) => { 
      // this code is executed when the promise resolves successfully
      console.log('this is the post that was saved. You can see that')
      console.log(' the id field is filled in by DataStore', post)
    })
    .catch((e) => { 
      // this code is executed if the promise resolves with an error
      console.log('there was an error creating the post', e)
    })