1

I have an object called "values" that contains a property "images" that is an array of strings. When I console.log "values", I do see the "images" property as an array of strings. However, when I console log values.images, the result is empty. How could this be?

Here's the react-redux code:

I'm calling the confirm method.

    const confirm = () => {

        console.log("form values in confirm");
        console.log(formValues);

        let images = [];
        for (let i = 0; i < formValues.images.length; i++) {
            var reader = new FileReader();
            reader.onload = function(e) {
                images.push(e.target.result);
                console.log('images base 64');
                console.log(images);
            };
            reader.readAsDataURL(formValues.images[i].file);
        }
        formValues["images"] = images;
        console.log("values after adding images");
        console.log(formValues);
        upload(formValues, history);
    };

This snippet is from the action creator:

export const upload = (values, history) => async dispatch => {
    console.log("images in uploadProduct action");
    console.log("the whole object");
    console.log(values);
    console.log("values.images");
    console.log(values.images);
};


-- edit --

The comments point out that the console.logs are lazily evaluated which is why I'm seeing the property when printing the whole object. Good to know. However, the goal is to in fact get the values.images property before further execution. How can I do that?

zengod
  • 1,114
  • 13
  • 26
  • You are populating the `images` array asynchronously. So, it's going to get the values *later* than the time of logging it. However, the console will [evaluate the object reference lazily](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) an show you *the latest state* of the array, not the state it was in when it was logged. – VLAZ Jan 10 '20 at 22:40
  • 1
    To address your edit, see [this post](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Ivar Jan 10 '20 at 22:44
  • @Ivar, .then vaguely seems to be applicable in this code but *how* is still a question. – zengod Jan 10 '20 at 22:46
  • @zengod The top answer in the post I mentioned shows several ways on how you can resolve that issue. (Under "Solution(s)".) – Ivar Jan 10 '20 at 22:48
  • [HTML5 FileReader how to return result?](https://stackoverflow.com/questions/11829537/html5-filereader-how-to-return-result) – VLAZ Jan 10 '20 at 22:50

0 Answers0