0

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?

Onaracs
  • 935
  • 3
  • 14
  • 22
  • Unrelated but Make sure to add a 'catch' handler in your request to camera roll to handle errors otherwise your app will crash – Maxwelll May 17 '16 at 23:37
  • Have you logged `data` in `CameraRoll.getPhotos()` to make sure the values aren't `undefined` before you you call `photosToBase64`? – Himmel May 17 '16 at 23:39
  • @Himmel yes, I have some additional code in my editor that I trimmed down for the purpose of the question, but when the data is passed to `photosToBase64()` it is defined properly. – Onaracs May 17 '16 at 23:49
  • I think you may need to return the line starting with `NativeModules.ReadImageData...`, so `return NativeModules.ReadImageData...` – Himmel May 17 '16 at 23:51
  • looks like the `return` statements are missing in the `this.photosToBase64` function and the result of the function is not assigned to a variable – Tom Goldenberg May 18 '16 at 01:24
  • try putting nesting `this.photosToBase64(data)` inside a conditional, like `if (data[0])`. Because it's an asynchronous promise, it may take a little bit before you actually have the data to work with. – Jared Rader May 18 '16 at 01:25

0 Answers0