I am using the fetch API to send a base64 photo to my backend for manipulation, and then I return it. I want to read the photo and write it to my cameraRoll, which I can do. The end goal is to share the photo to instagram, but for some reason the fileReader stops the props from updating. Here is the method:
uploadImageAsync = async (uri, setImageText) => {
let apiUrl = "some url"
let uriParts = uri.split('.');
let fileType = uri[uri.length - 1];
let formData = new FormData();
formData.append('photo', {
uri,
name: `photo`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options)
.then(response => {
return response.blob();
})
.then( async myBlob => {
const fileReader = new FileReader();
fileReader.readAsText(myBlob);
const objectURL = URL.createObjectURL(myBlob);
fileReader.addEventListener('loadend', async (e) => {
const text = e.srcElement.result;
this.props.setImageText(text);
let source = { uri: 'data:image/jpeg;base64,' + text };
const cameraRollAddress = await CameraRoll.saveToCameraRoll(source.uri, 'photo');
let instagramURL = `instagram://library?AssetPath=${cameraRollAddress}`;
Linking.openURL(instagramURL);
return;
});
});
}
The photo saves to the camera roll, but the props are not updated, so the Linking
doesn't happen until I press another button somewhere on the screen.
For instance, if I navigate to another screen, Instagram will open with the photo ready to be shared. It doesn't matter what props I try to update, even something as simple as changing the text on the screen: when I use the fileReader
, the props won't update. When I take that line out, the props will update, but I need it to get the base64 text string for the image.
Also, the base64 text string does save to the state (I'm actually using Redux), but nothing is updated.