Search code examples
javascriptdatabasereactjsamazon-dynamodbaws-appsync

Query a specific GET field?


How can I get just a single field (called "name") from an entry in my AppSync/Dynamo table, for a given "id:"? This is instead of getting the entire row of fields for that 'id' returned to me. I only need the single field.

The following doesn't work:

const userName = await API.graphql(graphqlOperation(GetUsers, { id: "3b342de-34k5-434....." }, "name") );

Schema:

type Users @model {
  id: ID!
  name: String
  email: String
}

Query:

export const getUsers = `query GetUsers($id: ID!) {
  getUsers(id: $id) {
    id
    name
    email
  }
}

Solution

  • Try below

    export const getUser = `query GetUsers($id: ID!) {
      getUsers(id: $id) {name}
    }`
    
    const userName = (await API.graphql(graphqlOperation(getUsers, {id: "xxx"}))).getUser.data.name
    

    Be aware that the await gives you a nested object that includes the name. You have to extract it out. Besides, what you really need is type User, not type Users.