I've got a massive list of about 50 dog photos that I'm pulling in from an API into a react component, and I only want to display the first 10. I wrote the following function to attempt to filter out only the first 10 photos url's in the array
setData = async () => {
const x = await fetch('https://dog.ceo/api/breed/hound/images')
const y = await x.json()
const z = await y.message
let newArr =[]
for (let i=0; i<z.length; i++){
if (i<=10){
newArr.push(z[i])
}
}
return newArr
}
then used the result of that to set the state
componentDidMount(){
const dogList = this.setData()
this.setState({
dog: dogList
})
}
....which then was supposed to render just the first 10 dog photos:
render() {
return (
<div>
<h1>Rate My Dogue</h1>
{
this.state.dog.map(doggie => {
return <img className = 'img' src = {doggie}></img>
})
}
</div>
);
}
}
and unsurprisingly, it didn't work. Does anyone have suggestions on how I can prune my API call?
Here's the full component:
import React from 'react';
import './styles.css'
class App extends React.Component {
constructor(){
super()
this.state = {
dog: []
}
}
setData = async () => {
const x = await fetch('https://dog.ceo/api/breed/hound/images')
const y = await x.json()
const z = await y.message
let newArr =[]
for (let i=0; i<z.length; i++){
if (i<=10){
newArr.push(z[i])
}
}
return newArr
}
componentDidMount(){
const dogList = this.setData()
this.setState({
dog: dogList
})
}
render() {
return (
this.state.loading ? <h1> Dogues Loading.....</h1>
:
<div>
<h1>Rate My Dogue</h1>
{
this.state.dog.map(doggie => {
return <img className = 'img' src = {doggie}></img>
})
}
</div>
);
}
}
export default App;