react loop data from api code example
Example 1: reactjs loop through api response in react
import React from 'react';
class Users extends React.Component {
constructor() {
super();
this.state = { users: [] };
}
componentDidMount() {
fetch('/api/users')
.then(response => response.json())
.then(json => this.setState({ users: json.data }));
}
render() {
return (
<div>
<h1>Users</h1>
{
this.state.users.length == 0
? 'Loading users...'
: this.state.users.map(user => (
<figure key={user.id}>
<img src={user.avatar} />
<figcaption>
{user.name}
</figcaption>
</figure>
))
}
</div>
);
}
}
ReactDOM.render(<Users />, document.getElementById('root'));
Example 2: react fetch data in for loop
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})
}
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})
}
}