I have made it like this, this is not an error but I also do not understand, if the issue is my setup or the problem with wp-graphql-upload.
register_graphql_mutation('uploadProfilePicture', [
'inputFields' => [
'file' => [
'type' => 'Upload',
],
],
'outputFields' => [
'avatarUrl' => [
'type' => 'String',
'resolve' => function ($payload) {
return $payload['avatarUrl'];
}
],
'avatarUrlThumbnail' => [
'type' => 'String',
'resolve' => function ($payload) {
return $payload['avatarUrlThumbnail'];
}
],
'successMessage' => [
'type' => 'Boolean',
'resolve' => function ($payload) {
return $payload['successMessage'];
}
]
],
'mutateAndGetPayload' => function ($input, $context, $info) {
if (!function_exists('wp_handle_sideload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$file_return = wp_handle_sideload($input['file'], [
'test_form' => false,
'test_type' => false,
]);
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
throw new \GraphQL\Error\UserError("The file could not be uploaded.");
}
$filename = $file_return['file'];
$attachment = [
'guid' => $file_return['url'],
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
];
$attachment_id = wp_insert_attachment($attachment, $filename);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attach_data);
update_field('profile_pic', $attachment_id, 'user_' . $current_user->ID);
$profile_pic = get_field('profile_pic', 'user_' . $current_user->ID);
$avatarUrl = $profile_pic['url'];
$avatarUrlThumbnail = $profile_pic['sizes']['thumbnail'];
return [
'avatarUrl' => $avatarUrl,
'avatarUrlThumbnail' => $avatarUrlThumbnail,
'successMessage' => true,
];
}
]);
const UPLOAD_IMAGE_MUTATION = gql`
mutation UploadProfilePicture($input: UploadProfilePictureInput!) {
uploadProfilePicture(input: $input) {
avatarUrl
avatarUrlThumbnail
}
}
`;
const selectImage = async () => {
// Check for the permission
const permissionResult =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("You've refused to allow this app to access your photos!");
return;
}
// Open the image picker
let pickerResult = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true, // or false based on your requirement
aspect: [4, 3], // aspect ratio
quality: 1, // quality of the image
});
if (pickerResult.canceled === true) {
return;
}
// Access the selected asset
const selectedAsset = pickerResult.assets[0]; // Assuming single image selection
if (selectedAsset) {
const source = {
uri: selectedAsset.uri,
type: selectedAsset.type, // type is now part of the asset
name: selectedAsset.fileName || "profile-pic.jpg", // name can be accessed or set a default
};
console.log(source);
uploadImage(source);
} else {
console.error("No image selected");
}
};
const [uploadProfilePicture] = useMutation(UPLOAD_IMAGE_MUTATION);
const uploadImage = async (imageFile) => {
// Convert image file to a format suitable for GraphQL upload
let localUri = imageFile.uri;
let filename = localUri.split("/").pop();
// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : imageFile.type;
// Prepare the formData
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
console.log("Form Data Prepared:", formData);
try {
console.log("Sending request to server");
const response = await uploadProfilePicture({
variables: {
input: { file: imageFile }, // Modify here to match the GraphQL mutation
},
});
console.log("Response received:", response);
// Extract the data from the response
const { avatarUrl, avatarUrlThumbnail, successMessage } =
response.data.uploadProfilePicture;
if (successMessage) {
console.log(successMessage); // Log or handle the success message as needed
// Update user context with new image URLs
setUserData({ avatarUrl, avatarUrlThumbnail });
}
} catch (error) {
console.error("Error during image upload:", error);
console.error("Error details:", error.networkError?.result || error);
}
};