In my small react Project, I needed to use an id from one api call in subsequent api calls. I have access to the data from the first call but do not know how to use it in the second call. I tried using a string literal to access all the ids so the URL can pick each ids directly from the other API but it was just returning random IDs.
Here is my code below
import React, { Component } from "react";
import axios from "axios";
export default class Cat extends Component {
state = {
imagedata: [],
data: [],
CatWeight: "",
CatMetric: "",
}
componentDidMount(){
this.fetchCountryData();
this.fetchImageUrl();
}
fetchCountryData = async () => {
const url = "https://api.thecatapi.com/v1/breeds";
try {
const response = await axios.get(url);
const data = await response.data;
console.log(data)
this.setState({
data,
});
} catch (error) {
console.log(error);
}
};
fetchImageUrl = async () =>{
// This is the Place I'm having issue with. The line below. where imgurl becomes https://api.thecatapi.com/v1/images/search?breed_id=char as an example
// The id is coming from the First API id's
const imgurl = `https://api.thecatapi.com/v1/images/search?breed_id=${this.state.data.map((item) => { return item.id })} `
try {
const response = await axios.get(imgurl);
const imagedata = await response.data;
console.log(imagedata)
this.setState({
imagedata,
});
} catch (error) {
console.log(error);
}
};
render() {
return (
<div>
{
this.state.imagedata.map((item, id) =>{
return <ul key={id}>{item.id}</ul>
})
}
</div>
)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…