0

When I have Two APIs and one for cats data and one for cats image, how can I populate images and data from two APIs in one component using hooks through Axios call?

CodeSandbox

CatsList.js

import React, {useState, useEffect} from 'react'
import {baseUrl} from './services/mainApi';
import axios from 'axios';

export default function CatsList() {
  const [data, setData] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `${baseUrl}breeds`,
      );
      setData(result.data);
    };
    fetchData();
  }, []);

  return (
    <ul className="row">
      {data.map(item => (
        <li className="col-md-3 list-item" key={item.id}>
          <a href={item.wikipedia_url}>
            <h2>{item.name}</h2>
            <p>{item.origin}</p>
            <p>{item.description}</p>
          </a>
        </li>
      ))}
    </ul>
  );
}

mainApi.js

import axios from 'axios';
export const baseUrl = 'https://api.thecatapi.com/v1/'
export const catsImage = `${baseUrl}/images/search?breed_id=abys`

1 Answer 1

1

You'll need to make a a request per cat to get the cats image, before setting data e.g.

const fetchData = async () => {
    const result = await axios(
        `${baseUrl}breeds`,
    );
    const catImageResponses = Promise.all(
        result.data.map(cat => axios(buildCatImageUrl(cat)))
    )
    // handle catImageResponses, correlating them with result.data (cats), then set state
};
fetchData();

You'll need to correlate your cat images with your cats before setting your state, and you'll need to build the cat image url dynamically based on the cat, at the minute its hardcoded.

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

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.