[英]Call an API from another API using Axios and React
我正在使用以下 function 從口袋妖怪 api 獲取數據(結果):
const [data, setData] = useState({ results: []})
useEffect(() => {
const fetchData = async () => {
const response = await api.get('/pokemon');
setData(response.data);
};
fetchData();
}, []);
我的 API function:
const api = axios.create({
baseURL: 'https://pokeapi.co/api/v2'
});
這就是我的回應
{
"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.
]
如何從結果數組中 object 內部的 url 執行獲取請求?
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();
}, []);
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
};
或者,您可能希望遍歷結果
for(const result of response.data.results){
const { url } = result;
const reponse = axios.get(url);
// do something with response
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.