there is a code

const fetchData = { data: [], ft(){ fetch('http://127.0.0.1:8000/api/v1/') .then(response => response.json()) .then(data => this.data.push(data)) .finally(() => { document.getElementById("myButton").style.backgroundColor = 'red'; // return this.data // console.log(this.data) }) .catch(error => console.log(error)) console.log(this.data) }, mapFt(){ console.log(this.ft()) //.map(i => console.log(i)) } } export default fetchData.ft() 

which returns this enter image description here

how do i pick up data from there?

Reported as a duplicate at Grundy. javascript May 10 at 14:38 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • No, he writes that he cannot read the data property a lot of things he tried, because of this, this question on stackoverflow turned out - htaccess
  • probably just this. data [0] - trollingchar
  • this.data [0] will return undefined - htaccess
  • .then (data => this.data = data) - Rustam Gimranov
  • returns an empty array - htaccess

2 answers 2

Here it is necessary to use promises, because at first fetch(...) is called asynchronously, it does not have time to write data.

Try something like this:

 async ft() { new Promise((res, rej) => { fetch('http://127.0.0.1:8000/api/v1/') .then(response => response.json()) .then(data => this.data.push(data)) .finally(() => { document.getElementById("myButton").style.backgroundColor = 'red'; res() // return this.data // console.log(this.data) }) .catch(error => console.log(error)) }).then(() => console.log(this.data)) }, 
  • go fuck manuals - htaccess
  • htaccess, so can you smoke if you ask such questions. more and incorrect - teamspam
  • one
    fetch(...) returns promise by itself. No need to wrap it. Just the vehicle does not indicate where it calls its function. Therefore, does not receive detailed answers. - Rustam Gimranov
  • one
    const response = await fetch(); const data = await response.json() - Rustam Gimranov
  • one
    The answer came out of discharge bad advice) - Stepan Kasyanenko

short version

  async ft(){ const response = await fetch('http://127.0.0.1:8000/api/v1/') const data = await response.json() .finally(()=>{ document.getElementById("myButton").style.backgroundColor = 'green'; }) console.log(data.data) return data } 

what offered Rustam