How to pass a variable holding a string to a GraphQL query via the AWS AppSync client?

1.6k Views Asked by At

I am using React JS app to submit data with the AWS AppSync client and a GraphQL API to a NoSQL Table in the cloud. I autogenerated the GraphQL operations with AWS Amplify and now I am attempting to submit the following operation in my React code: (note and company are mere string values held in React's state)

  createOffer(note, company) {
    const input = {
            place: company,
            title_de: note,
            category: "product",
        }
    return API.graphql(graphqlOperation(mutations.createOffers, {input: input
    }));

This produces an exception "[object Object]"

Now if I pass the strings in directly like so

  createOffer() {
    const input = {
            place: "Example Company ",
            title_de: "Example Title",
            category: "product",
        }
    return API.graphql(graphqlOperation(mutations.createOffers, {input: input
    }));

it works fine. The only workaround I've found so far is to wrap the variables holding string values in JSON.stringify(company) and JSON.stringify(note). But then the corresponding database entries are wrapped in double quotes "Example Company" rather than Example Company.

I want to avoid manually modifying the autogenerated GraphQL API code since I expect it to change frequently.

Is there an option on the client side to get the actual string from React state into the API call without GraphQL identifying it as an object or it ending up with double quotes in the database?

1

There are 1 best solutions below

1
On BEST ANSWER

Have you tried template literals?

const input = {
  place: `${company}`,
  title_de: `${note}`,
  category: 'product'
}

When I ran a quick test in the dev console, that definitely removes the extra quotes that you have been experiencing.