How to upload Image using graphQL update mutation in Keystone6?

640 Views Asked by At

I am trying to upload user profile image using useMutation But I am getting 400 error while uploading.

here is my code.

File Input

<input type="file" multiple required onChange={onChange} />

onChange

 function onChange({ target: { validity, files } }: any) {
        if (validity.valid) {
            try {
                updateUserImage({
                    variables: { files: { upload: files[0] } },
                });
            } catch (error) {
                console.log(error);
            }
        }
    }

updateUserImage

const [updateUserImage] = useMutation(updateProfileImageQuery);

const updateProfileImageQuery = gql`
    mutation ($files: Upload!) {
        updateUser(
            data: { avatar: $files }
            where: { id: "ckx8qymsv0046iol87cszngcn" }
        ) {
            name
        }
    }
`;
1

There are 1 best solutions below

0
On

I have done the job using native fetch to send graphQL mutation:

export const useGqlFile = async () => {
  const formData = new FormData();
  const query = `
    mutation ($data: InputType!) {
      item: createModel(data: $data) {
        id
        file {
          filename
          url
        }
      }
    }
  `;

  formData.append(
    "operations",
    JSON.stringify({
      variables: {
        data,
      },
      query,
    }),
  );

  formData.append("map", '{"1":["variables.data.file.upload"]}');
  formData.append("1", file, file?.name);


  const response = await fetch(
    `${runtimeConfig.public.BACKEND_URL}/api/graphql`,
    {
      method: "POST",
      body: formData,
      headers: {
        authorization,
      },
    },
  );

  return response;
};