I have a page, (index.js) which contains component (slider.js). On index.js I am consuming 2 separate API. Everything works if I send the data from the 1st API to 1 component, and the data from the 2nd API to a different component.
However, I want a single component to receive some of the values from the 1st API along with some of the values from the 2nd API.
export default class extends React.Component {
static async getInitialProps() {
const apiUrl = 'https://api-1.com'
const res = await fetch(apiUrl)
const data = await res.json()
const apiUrl2 = 'http://api2.com'
const params2 = 'featured'
const res2 = await fetch(apiUrl2)
const data2 = await res2.json()
return { data, data2 }
}
componentDidMount() {
//logPageView()
}
render() {
return (
<div id='slider'>
{this.props.data.map(function (post, i) {
return (
<Slider
api1postSlug={post.slug}
//api2category={post2.slug}
/>
)
})}
</div>
}
How would I pass the props from data2 along with {this.props.data.map(function (post, i) {
Assuming that API 2 has the same data structure and rows of API 1 , you can do it like so:
export default class extends React.Component {
static async getInitialProps() {
const apiUrl = 'https://api-1.com'
const res = await fetch(apiUrl)
const data = await res.json()
const apiUrl2 = 'http://api2.com'
const params2 = 'featured'
const res2 = await fetch(apiUrl2)
const data2 = await res2.json()
return { data, data2 }
}
componentDidMount() {
//logPageView()
}
render() {
return (
<div id='slider'>
{this.props.data.map(function (post, i) {
return (
<Slider
api1postSlug={post.slug}
api2category={this.props.data2[i].category}
/>
)
}, this)}
</div>
}
}
}
Try adding an if condition before returning as following.
render() {
if(this.props.data && this.props.data2) {
return (
<div id='slider'>
{this.props.data.map((post, i) => {
return (
<Slider
api1postSlug={post.slug}
api2category={this.props.data2[i].category}
/>
)
}, this)}
</div>
)
} else {
return (
<div id='slider'>Loading...</div>
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.