How does Datastore work with ReactJS to insert the user ID into the "owner" field of a GraphQL type ?

0

Hi !

How can I make "DataStore" framework insert the user.attribute.sub or user.username into the "owner" field of a GraphQL type?

This guys did that: https://youtu.be/D8gSc7wDRic?si=tmF1f7j-hr5RkJx_

I see that they only used "datastore.save" command, and as you can see, they didnt filled "owner" inside the app. Also, they make the React app compare the user.attributes.sub with the post.owner field and the app automatically recognized that they were the same.

I used that datasore.save command but the "owner" field is "null". I even tryed to set it manually, but it simply doesnt recieve the ID.

My code actually creates the post, but the "owner" field is empty. My process was: I created the Schema in my Code Editor, then I push it to Amplify Studio. It created the types in the "data" section. After that, I enabled the "Enable owner authorization" in Amplify Studio in the "Post" type.

The "Post" type has this Authorization Rules: Authenticated and unauthenticated scopes: Anyone authenticated with API Key can Create, Read, Update, and Delete Product

The "Post" type has: Owner-based scopes:

Enable owner authorization (yes, enabled) Owner-based authorization allows you to tie a data record to a user. Owners can read, create, update, and delete the record.

Allow the owner to perform these operations on their own records: Create, Read, Update, Delete

After that, the "Post" type got an additional field called "owner". Once I pulled the changes to my code editor, there schema.graphql file didnt got the "owner" field, but you can see it in AWS AppSync.

It would be wonderfull if you could help me by telling me where can I add a "console.log" to check or see what is allowing to enter the new "post" but is preventing to put the "user ID" into the "owner" field. Or you can tell me if there is a Hub function, or DataStore.suscribe or similar to identify that. It can be an option if you tell me if the error can be identified with CluodWatch or any other service that reads every answer received and answered by the server.

This is the code of the two files, "index.js" and "Apps.js":

index.js

import { Amplify, API, graphqlOperation, Interactions, Auth, AuthModeStrategyType } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';
import awsconfig from './aws-exports';
Amplify.configure({
  ...awsconfig,
  DataStore: {
    authModeStrategyType: AuthModeStrategyType.MULTI_AUTH
  }
});

App.js

import { Amplify, API, graphqlOperation, Auth } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';

const App = ({ signOut, user }) => {
  const [post, setPost] = useState('');
  const [blogID, setBlogID] = useState('');
  // AWS Video
  const [currentUser, setCurrentUser] = useState();

  const handleSubmit = async (e) => {
    e.preventDefault();
    async function checkLoginState() {
      try {
        const currentUser = await Auth.currentAuthenticatedUser();
        if (currentUser) {
          console.log('Usuario autenticado con Auth:', currentUser);
          setCurrentUser(currentUser);
        }
      } catch(err) {
        console.log('No se pudo atenticar el usuario:', err);
      }
    };
    checkLoginState(); // It succesfully brings the user JSON object from Cognito

    // Create a new post
    const post = new Post({
      content,
      blogID,
    });
    
    // Save the post to the DataStore
    await DataStore.save(product);

    // Reset the form inputs
    setPost('');
    setBlogID('');
    // Display a success message
    alert('Posted successfully');
  };
..


return..
    <div className="add-post-form">
      <h2>Agregar Post</h2>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="post-post">Post</label>
          <TextField
            id="post-post"
            style={styles.input}
            value={post}
            onChange={(e) => setPost(e.target.value)}
            placeholder="What do you want to share..."
            required
          />
        </div>
        <button type="submit">Add Post</button>
      </form>
    </div>
...

export default withAuthenticator(App);
asked 6 months ago138 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions