Search code examples
amazon-web-servicesgraphqlaws-amplifyaws-appsync

How to avoid creating duplicate items in an array when posting an AWS Amplify GraphQL mutation


Preface: I'm new to GraphQL and Amplify.

I have a user object that contains two arrays, one called preferred_genres, and another called preferred_characters. I have a profile page where the user can edit their profile and add items to these arrays.

The update mutation provided by AWS Amplify seems only to be adding elements to the array, never removing them. If on my UI I remove an item from the list and then submit the update mutation, the item is not removed from my backend. If I add an item to the array, the item is added on the backend, but I also end up with duplicate values for those already in the backend.

What I'm trying to do is overwrite the array on the backend with the data I'm submitting from the front end. Am I missing something obvious? Is there a more appropriate way of achieving this in GraphQL?

Schema

type User @model {
  id: ID!
  ...
  preferred_characters: [Character]
  preferred_genres: [Genre]
  ...
}

Screenshot of Profile showing duplicate items in array Screenshot of database on backend showing duplicate items in array


Solution

  • I stumbled upon this question in the Amplify GitHub issues about the AWSJSON scalar having a similar issue. The issue seems to be related to conflict resolution in the API.

    I don't remember setting that up, but I tried amplify update API, chose my GraphQL API and the advanced options, declined any conflict resolution and ran amplify push.

    Now values are saving as expected. When I remove an item from an array it's removed from the backend and visa-versa.