Search code examples
djangoreactjsgraphqlgraphene-django

graphene mutation returns 400 - won't pass id field properly


I have been using graphene in django with graphql and a React frontend.

I can get a create mutation to work, but an edit one won't - even tho the query without $ variables works in graphiQL

My gql const in React is:

export const EDIT_PERSON = gql`
  mutation personEdit($id: id, $input: PersonInputType!) {
    personEdit(id: id, input: $input) {
      person {
        id
      }
    }
  }
`;

id is set from a handler and the submit function in the form looks like:

<form
          autoComplete="off"
          onSubmit={e => {
            e.preventDefault();
            editPerson({
              variables: {
                id: id,
                input: {
                  firstName: firstName,
                  lastName: lastName,
                  address: address
                }
              }
            });
          }}
        >

My PersonEdit mutation in django looks like:

class PersonEdit(Mutation):
    class Arguments:
        id = ID(required=True)
        input = PersonEditInputType(required=True)
    person = Field(PersonType)

    @classmethod
    def mutate(cls, root, info, **data):
        serializer = PersonSerializer(data=data.get('input'))
        serializer.is_valid(raise_exception=True)
        person = Person.objects.get(id=data.get('id'))
        print("PERSON", serializer.data)
        person.first_name = serializer.data['first_name']
        person.last_name = serializer.data['last_name']
        person.address = serializer.data['address']
        return PersonEdit(person=person.save())

Why will editing not work?


Solution

  • Your mutation should look like this

    export const EDIT_PERSON = gql`
      mutation personEdit($id: ID!, $input: PersonInputType!) {
      personEdit(id: $id, input: $input) {
        person {
          id
        }
       }
     }
    `;
    

    Here it should be id: $id not id: id.