Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react fetch data in for loop

/*
ORIGINAL CODE
*/

videoUrls=()=>{
  let i=0;
  let urllist=[]
  for(i;i< this.state.data.length;i++){
      fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${this.state.data[i].name}&key=xxxxxxxxxxx0`)
      .then(response=> {
        return response.json()
    })
     .then(data=>{
        return(urllist.push(data.items[0]))
      })
   }
   console.log({urllist})
}

/*
Your for loop does not iterate asynchronously but you can get around 
this by putting your for loop inside an async function Asynchronous 
Process inside a javascript for loop and awaiting the result of the 
asynchronous operations
*/

/*
New code
*/

videoUrls = async () => {
  let i=0;
  let urllist=[]
  for(i;i< this.state.data.length;i++){
      const response = await fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${this.state.data[i].name}&key=xxxxxxxxxxx0`)
      const json = await response.json()
      urllist.push(json.items[0])
      console.log({urllist})
    }
 }
Comment

PREVIOUS NEXT
Code Example
Javascript :: get element by id two ids 
Javascript :: JavaScript catch() method 
Javascript :: angularjs form validation on submit 
Javascript :: javascript select2 sortable 
Javascript :: sorting an array based on certain element 
Javascript :: alpine js x-on click not working 
Javascript :: react native ant design 
Javascript :: moment.js get time from now 
Javascript :: coreui react change background color 
Javascript :: webpack.config.js 
Javascript :: moment js date between two dates 
Javascript :: response intersepters for axios create 
Javascript :: how to change the text of a paragraph 
Javascript :: electron in webpack 
Javascript :: of rxjs 
Javascript :: server mail 
Javascript :: javascript form data 
Javascript :: two dimensional array in javascript 
Javascript :: push array into array javascript 
Javascript :: js delete all from array 
Javascript :: convert positive to negative number javascript 
Javascript :: login with facebook expo react native 
Javascript :: upload photos cypress 
Javascript :: amcharts 
Javascript :: jquery repeat event on click 
Javascript :: updatig state in react 
Javascript :: array merge in javascript 
Javascript :: jsx react 
Javascript :: use the AJAX XMLHttpRequest object in Javascript to send json data to the server 
Javascript :: react native cli sdk.dir 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =