0

This is just a question to help my understanding of what is going on under the hood.

If I write a simple JS file to fetch data, like below, I can call .then() and provide the name of the function that the microtask queue will run. The parens get added for me and the data argument is injected. Everything works.

function displayMovie(data:object){
        console.log(data)       
    }


 const movie =    fetch('https://swapi.dev/api/people/1');
        movie.then(response => response.json())
            .then(displayMovie)

But in an LWC I have to specific this.displaymovie(data) or the callback will never run. I assume it never makes it onto the microtask queue at all.

import {LightningElement} from 'lwc';

export default class Fetch extends LightningElement {



    connectedCallback() {
        this.getMovie();
    }

    getMovie(){
     const movie =    fetch('https://swapi.dev/api/people/1');
        movie.then(response => response.json())
            .then(data => this.displayMovie(data))
    }

    displayMovie(data){
       console.log(data);
    }
}

I was hoping one of the JS pros could help explain what makes the class model different. I am assuming it is not an LWC specific thing.

1 Answer 1

1

You don't need the arrow function, but you do need this:

.then(this.displayMovie)

This is because in ES6 classes, you must use this to access class properties, including functions.

However, it's usually desirable to use the arrow function to make sure that this is set to the correct context.

1
  • Got it, I am not sure why I did not take the arrow function into consideration. And that required adding the arguments vs letting the JS engine inject them. Dec 10, 2021 at 15:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .