简体   繁体   English

使用 Axios 和 React 从另一个 API 调用 API

[英]Call an API from another API using Axios and React

I'm using the following function to get data (results) from the pokemon api:我正在使用以下 function 从口袋妖怪 api 获取数据(结果):

    const [data, setData] = useState({ results: []})


    useEffect(() => {
        const fetchData = async () => {
            const response = await api.get('/pokemon');
            setData(response.data);
        };
        fetchData();
    }, []);

My API function:我的 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?如何从结果数组中 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. 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
};

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM