-1

I have the following code

It returns a string when in the reader.onload function but null when i console.log image.Url in the outer function

EDIT: This is the full code


export default {
  data() {
    return {
      item: {
        image: null
      },
      imageUrl: null,
    };
  },

  methods: {,
    uploadImage(e) {
      let image = e.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(image);

      reader.onload = function(){
        this.imageUrl = reader.result
        console.log(this.imageUrl)
        // this.setImageOne(this.imageUrl)
      }
      console.log(this.imageUrl)
      

    },

EDIT:

Fixed it. Thanks everyone

  • how is the outer code? from what you show, you could remove the `this`, and everything should work fine. – Mario Vernari Oct 17 '21 at 05:42
  • What would you expect the code to log if `onload` hadn't completed? – Andy Oct 17 '21 at 05:42
  • also, besides the asynchronous issue, `this` inside your `onload` function vs the `this` in your `uploadImage()` method most likely represent different objects – Nick Parsons Oct 17 '21 at 05:45
  • i just uploaded the full code. I need to call this to access the variable – Rippyblogger Oct 17 '21 at 05:48
  • you can perform the code that relies on `reader.result` inside of your `onload` function, not outside of it in the `uploadImage()` function. Otherwise, if you intend to use it outside of the onload function, you need to ensure that code only runs after your onload function has set the value for it (which is usually only done if that code executes by some other event that can occur after the load occurs such as a click) – Nick Parsons Oct 17 '21 at 05:52
  • i actually need to use it outside the function and i'm stumped and at my wits end currently – Rippyblogger Oct 17 '21 at 06:45

1 Answers1

0

Things aren't happening in the order you expect.

This is the order they are happening:

  1. uploadImage() called
  2. the second console.log runs and imageUrl is null (the callback function is registered for the onload event)
  3. the onload callback is run and imageUrl is set
 function(){
        this.imageUrl = reader.result
        console.log(this.imageUrl)
        // this.setImageOne(this.imageUrl)
      }

This function is not run when it is defined. Js only runs the callback function you provide when the onload event happens. It registers this callback and then continues on to the console.log.

If you want to use the value of imageUrl you should do that in the callback function.

nlta
  • 1,716
  • 1
  • 7
  • 17
  • So there's no way to use it out of the callback then? – Rippyblogger Oct 17 '21 at 06:44
  • You can use it out of the callback you just can't be sure it's been set yet. What are you trying to do that doesn't make sense to do in the callback? – nlta Oct 17 '21 at 07:05