chai86
chai86

Reputation: 443

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
  }
}

Upvotes: 0

Views: 1087

Answers (2)

Magnum
Magnum

Reputation: 2395

Your query is querying getUsers from your graphql server, and is asking for id, name, and email.

If you only want the name, change the query to this:

query GetUsers($id: ID!) {
  getUsers(id: $id) {
    name
  }
}

Upvotes: 0

yiksanchan
yiksanchan

Reputation: 1940

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.

Upvotes: 1

Related Questions