Reputation: 587
We have the following state in react:
state = {
thumbnail: [],
title: [],
}
Which gets set after we retrieve some data from themoviedb
api, like
axios.get(
`http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&with_genres=28,99&api_key=${apiKey}`
)
.then(res => {
const thumbnail = res.data.results.map(res => res.poster_path)
const title = res.data.results.map(res => res.original_title)
this.setState({ thumbnail, title })
// console.log(posterPath);
})
So our state will look like :
thumbnail: ['url1', 'url2'] // 20 entries
title: ['title1', 'title2'] // 20 entries, too
Then I want to render a list which has to take these two props as values and Display them, but I don't know how to, what I've tried is:
{Object.entries(this.state).map((url,i) => {
console.log(url[1]);
return(
<ImageCard
key={i}
source={{uri: 'http://image.tmdb.org/t/p/w342'+url.thumbnail}}
style={{width: width * 0.3, height: height * 0.3, margin: 3}}
title={url.title}
/>
);
})}
But it doesn't work, i wanna map over the whole state object So i won't have to do two maps, anyone has any ideea how can I map over this data structure?
Upvotes: 0
Views: 1505
Reputation: 307
You could just do the following instead of 2 maps, if the 2 arrays will be the same length
{this.state.title.map((title, i) => {
return(
<ImageCard
key={i}
source={{uri: 'http://image.tmdb.org/t/p/w342'+this.state.thumbnail[i]}}
style={{width: width * 0.3, height: height * 0.3, margin: 3}}
title={title}
/>
);
})}
Upvotes: 1
Reputation: 17868
Since the thumbnail and title are related with each other, I would keep only one array inside the state like this:
state = {
data: []
}
Changing to axios.get like this:
axios.get(
`http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&with_genres=28,99&api_key=${apiKey}`
)
.then(res => {
let temp = res.data.results.map(item => {
return {
thumbnail: item.poster_path,
title: item.original_title
}
})
this.setState({ data: temp })
})
And displaying the ImageCard like this:
this.state.data.map((item, index) => {
return (
<ImageCard
key={index}
source={{ uri: 'http://image.tmdb.org/t/p/w342' + item.thumbnail }}
style={{ width: width * 0.3, height: height * 0.3, margin: 3 }}
title={item.title}
/>
);
})
Upvotes: 1