javascript – Sending array of objects in mutation – GraphQL
I have such GraphQL mutation from backend.
mutation{
errorReportForm(input: {
email:"userEmail",
name:"User Name",
description:"Some description."
attachments: [{
name:"imageName.png"
type:"image/png"
file:"iVBORw0KGgoAAAANSUetc.tłu="
}
]}){
admin_mail_sent
client_mail_sent
description
email
name
}
}
So i wrote this mutation like here:
const errorReportFormMutation_withAttachment = gql`
mutation errorReportForm_withMutation(
$email: String!
$firstname: String!
$description: String!
$name: String!
$type: String!
$file: String!
) {
errorReportForm(
input: {
email: $email
name: $firstname
description: $description
attachments: [{ name: $name, type: $type, file: $file }]
}
) {
admin_mail_sent
client_mail_sent
description
email
name
}
}
`;
And a function to send form (await errorReportForm_withAttachment from mutation with attachments, await errorReportForm if without).
const handleSendBugReport = useCallback(
attachments => async ({ email, firstname, description }) => {
try {
if (attachments.length > 0) {
await errorReportForm_withAttachment({
variables: {
email,
firstname,
description,
name: attachments[0].name,
type: attachments[0].type,
file: attachments[0].file
}
});
} else {
await errorReportForm({
variables: {
email,
firstname,
description
}
});
}
} catch {
return;
}
},
[errorReportForm, errorReportForm_withAttachment]
);
return {
errorReportFormData,
errorReportFormLoading,
errorReportFormError,
errorReportFormData_withAttachment,
errorReportFormLoading_withAttachment,
errorReportFormError_withAttachment,
handleSendBugReport
};
};
How should I write this part if I want to send more than one attachment (attachments is an array in State)? The customer should be able to send from one to three attachments.
await errorReportForm_withAttachment({
variables: {
email,
firstname,
description,
name: attachments[0].name,
type: attachments[0].type,
file: attachments[0].file
}
Or should I maybe change something in a mutation?
Read more here: Source link