Reputation: 75
I'm using the following function to get data (results) from the pokemon api:
const [data, setData] = useState({ results: []})
useEffect(() => {
const fetchData = async () => {
const response = await api.get('/pokemon');
setData(response.data);
};
fetchData();
}, []);
My API function:
const api = axios.create({
baseURL: 'https://pokeapi.co/api/v2'
});
And this is the response I have
{
"count": 964,
"next": "https://pokeapi.co/api/v2/pokemon?offset=20&limit=20",
"previous": null,
//data that I need to use
"results": [
{
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
//the get request in the URL above can work both with name or number in pokedex.
},
//the list goes on till the 20th pokemon.
]
How can I perform a get request from the url that's inside of the object in results array?
Upvotes: 0
Views: 1691
Reputation: 6837
If you want the response and the details for each individual pokemon from you API you map over the response.results
and use Promise.all
to make a series of API calls and resolve it.
useEffect(() => {
const fetchData = async () => {
const response = await api.get('/pokemon');
// if you want to get the details as well
// details.data will be an array with details for all the pokemon that you get
// from response
const details = await Promise.all(response.data.results.map((el) => {
return axios.get(`/pokemon/${el.name}`)
}));
};
fetchData();
}, []);
Upvotes: 1
Reputation: 443
const fetchData = async () => {
const response = await api.get('/pokemon');
setData(response.data);
const { url } = response.data.results[0];
const reponse2 = axios.get(url);
// do what you want with response2
};
alternatively, you may want to loop through the results
for(const result of response.data.results){
const { url } = result;
const reponse = axios.get(url);
// do something with response
}
Upvotes: 0