alexdicorp's avatar

JS + Alpine.js inject variable

Hi guys! Using Laravel + Alpine.js

This function working best:

function dataIndex(url, rows) { 
    return { 
        url: "/" + url, 
        rows: rows, 
        refresh() { 
            fetch(this.url + "?api") 
                .then(response => response.json()) 
                .then(result => { 
                    this.rows = result; 
                })
                .catch(error => { 
                    console.log(error); 
                })
                .finally(result => {}); 
            }, 
    } 
}

I would like extern fetch in function:

function fetchGET(url, success = null) {
    fetch(url)
        .then(response => response.json())
        .then(result => {
            if (success) success(result);
        }).catch(error => {
        console.log(error);
    }).finally(result => {
    });
}
function dataIndex(url, rows) {
    return {
        url: "/" + url,
        rows: rows,
        refresh() {
			fetchGET(this.url + "?api", function (response) {
				this.rows = response; // NOT WORKING, HOW GET this.rows ??? BECAUSE 'this' -> Window {window: Window...
            })
        }
	}
}

Thanks

0 likes
2 replies
EmilMoe's avatar
EmilMoe
Best Answer
Level 10

Either use an arrow function, set self = this or .bind(this)

fetchGET(this.url + "?api",(response) => {
}).bind(this)
refresh() {
  let self = this
  fetchGET(this.url + "?api", function (response) {
    self.rows = response;

Please or to participate in this conversation.