I'm building an app in React Native and I'm having trouble understanding JavaScript callbacks.
On a button click I'm getting a set number of images from a user's Camera Roll (in this case, 2), and sending them to a function to convert each image reference to a base64 string to be saved later in a database. While I would like this function to return an array of base64 strings to send to my server I am instead getting returned an array of undefined
values.
I'm using lodash to map over each image returned to me from the Camera Roll.
The changeValue
function is called on a button click, which triggers getting the Camera Roll.
changeValue() {
CameraRoll.getPhotos({first: 2}).then((data) => {
this.photosToBase64(data); // this is returning [undefined, undefined]
// Send array of images to Node server when array values aren't undefined
}
}
photosToBase64(data) {
return _.map(data.edges, (dataNode) => {
const uri = dataNode.node.image.uri;
NativeModules.ReadImageData.readImage(uri, (base64String) => {
/**
* base64String is a string such as:
* '/9j/4AAQSkZ...'
*/
return base64String;
})
})
}
My goal is that this.photosToBase64(data)
will return an array of base64 strings (ie: ['/9j/4AAQSkZ...', '/9j/CDKEJ...']
that I can then send to my Node server to store in a database.
What is the best way to handle this? Should I wait in my changeValue()
function for the array to have actual values in them before I send it to my server?