⚠️ This lesson is retired and might contain outdated information.

Create New Posts using AWS Amplify's DataStore

Ali Spittel
InstructorAli Spittel
Share this video with your friends

Social Share Links

Send Tweet

To be able to create a new post, we can use AWS Amplify's DataStore. We are going to create a button that will prompt the user to fill in two fields, a title and the content. Then using DataStore.save we can save that user's post then console.log it to see that it will automatically auto-populated the owner's fields on the model when the new post is created.

Instructor: [0:00] We have authorization rules depending on whether or not a user is the owner of a model instance. We'll check how Data Store auto-populates the owner field so that we could conditionally render forms based on whether a user is an owner or not.

[0:15] First, I'm going to import Data Store from AWS Amplify. The last time we used Data Store, we used it on the server, so we used the "with server-side rendering" context in order to access it. This time we'll be using it in the browser, so we'll import it directly from the Amplify libraries.

[0:32] We'll also need to import our post model. Let's create a button on our user interface that a user will click it in order to create a new post. We'll add an event listener to the button. We'll implement the createPost function.

[0:58] Instead of writing out a full form, I'll use window.prompt in order to ask the user for a title and content. Now I'll create a new post instance. I'll also save that new post to data store.

[1:37] Since our posts belong to blogs, on each provide a blog ID for my post. Normally, you'd implement a drop-down or something along those lines to choose between the blogs. For brevity's sake, I'll just use the first blog as my blog ID. I want to view all my posts.

[1:53] I'll add a few more lines of code in order to first query them and then console.log them. First, we'll create a new post. Let's test this out in the console. See that the post has the owner field which has the ID of the user that created the post.

[2:16] You could check to see if this owner ID matches the ID of the current signed-in user and only show a Delete or Create button if the user is the owner. We created a new post and saw how the owner field was auto-populated on the model.