0

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?

0

2 Answers 2

1

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();
}, []);

Sign up to request clarification or add additional context in comments.

Comments

0
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.