Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

391
Visualizações
How do I target each image seperately, and fetch API data from them, instead of collect it all at once

I've created an app that connects to an API that retrieves dog images. On page load, 12 images are displayed, along with json text, that provides information about the breeds; height of the dog etc.

My final step would be somehow connecting the a button (which already exists) to each individual image, then retrieving data for that one specific dog/image after clicking it, instead of the API fetching all of the data at once on initial page load.

App.js

import './App.css';
import './Dog.js';
import './index.css';
import FetchAPI from './FetchAPI';




function DogApp() {

  return (
    
    <div className="dogApp">
     <FetchAPI />   
    </div>
  );
}

export default DogApp;

FetchAPI.js

import React, { useState, useEffect } from 'react'


const FetchAPI = () => {

    const [data, setData] = useState([]);
    const apiGet = () => {
        const API_KEY = "";
        fetch(`https://api.thedogapi.com/v1/images/search?limit=12&page=10&order=Desc?API_KEY=${API_KEY}`)
            .then((response) => response.json())
            .then((json) => {
                console.log(json);
                //setData([...data,json]); if json is single object
                setData([...data, ...json]); // if json is array of one object then use this line
            });
    };

    useEffect(() => {           //call data when pagee refreshes/initially loads 
        apiGet();
    }, []);

    return (
        <div>
            {data.map((item) => (
                <div class="dog">
                    <img src={item.url}></img>
                    <button onClick={item.breeds}>Fetch API</button>
                </div>
            ))}
            {data.map((item) => (
                <p>{JSON.stringify(item.breeds)}</p>
            ))}


            {/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
            <br />


        </div>

    )
}

export default FetchAPI;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Make an other function which will fetch new (single) image and change it to the state as I have made function named apiGetSingle which changes the data on specific index. And if you have made the route as I have mentioned in apiGetSingle which will return single new image then it will work fine otherwise made backend route for that too.

import React, { useState, useEffect } from 'react'


const FetchAPI = () => {

const [data, setData] = useState([]);
const apiGet = () => {
    const API_KEY = "";
    fetch(`https://api.thedogapi.com/v1/images/search?limit=12&page=10&order=Desc?API_KEY=${API_KEY}`)
        .then((response) => response.json())
        .then((json) => {
            console.log(json);
            //setData([...data,json]); if json is single object
            setData([...data, ...json]); // if json is array of one object then use this line
        });
};
 const apiGetSingle = (index) => {
    const API_KEY = "";
    fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
        .then((response) => response.json())
        .then((json) => {
            console.log(json);
            let d=[...data];
            d[index]=json; // if json is single object.
            d[index]=json[0] // if json returns array
            setData(d);
 };

useEffect(() => {        
}, []);

return (
    <div>
        {data.map((item,index) => (
            <div class="dog">
                <img src={item.url}></img>
                <button onClick={()=>apiGetSingle(index)}>Fetch API</button>
            </div>
        ))}
        {data.map((item) => (
            <p>{JSON.stringify(item.breeds)}</p>
        ))}

        <button onClick={apiGet}>Fetch API</button>
        {/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
        <br />


    </div>

)
}

export default FetchAPI;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda