Jade
Jade

Reputation: 90

String value cannot be saved to non-nullable variable

I've been trying to make a "CREATE_COMMENT" mutation work using GraphQL and Hasura for my frontend. However, when I tested the feature out, I kept getting the same error

enter image description here

Here is my Comment Component that uses CREATE_COMMENT mutation

function Comment({ postId }) {
  const classes = usePostStyles();
  const { currentUserId } = React.useContext(UserContext);
  const [content, setContent] = React.useState('');
  const [createComment] = useMutation(CREATE_COMMENT);

  function handleAddComment() {
    const variables = {
      content,
      postId,
      userId: currentUserId,
    };
    createComment({ variables });
    setContent('');
  }
  return (
    <div className={classes.commentContainer}>
      <TextField
        fullWidth
        value={content}
        placeholder='Add a commenet...'
        multiline
        maxRows={2}
        minRows={1}
        onChange={(event) => setContent(event.target.event)}
        className={classes.textField}
        InputProps={{
          classes: { root: classes.root, underline: classes.underline },
        }}
      />
      <Button
        color='primary'
        className={classes.commentButton}
        onClick={handleAddComment}
      >
        Post
      </Button>
    </div>
  );
}

See my mutation query below:

`export const CREATE_COMMENT = gql`
  mutation createComment($postId: uuid!, $userId: uuid!, $content: String!) {
    insert_comments(
      objects: { post_id: $postId, user_id: $userId, content: $content }
    ) {
      returning {
        id
        created_at
        post_id
        user_id
        content
        user {
          username
        }
      }
    }
  }
`;

See my Comment Table containing (id, post_id, user_id, created_at, and content) enter image description here

Am I doing something wrong related to Hasura or Apollo-client?

To debug the issue, I tried to make the content field "Nullable: True" and updated my mutation to the following:

mutation createComment($postId: uuid!, $userId: uuid!, $content: String)

This removed the warning and I thought it worked; however, when I checked my comment table in Hasura, the actual content value was recorded as NULL (so obviously, it didn't work)

I also tried to make the type be not restrict by adding [String!], but this didn't work either.

And I also checked out all the previous similar questions asked and answered but they were not helpful either.

Upvotes: 0

Views: 49

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

I suspect that where you have:

onChange={(event) => setContent(event.target.event)}

You should have:

onChange={(event) => setContent(event.target.value)}

You might also consider disabling your button when content === ''

Upvotes: 2

Related Questions