Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
Displaying an image from an API In React

I am trying to display the image of the breed selected by the user in this code but it is not working,

any ideas or hints as of why?

Thank you

import React, { useState, useEffect } from 'react';
import './breed-image.css';

function BreedImage () {
    const [breed, selectedBreed] = useState('');

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

    const fetchImage = async () => {
        const res = await fetch(`https://dog.ceo/api/breed/${breed}/images/random`)
        const data = await res.json();
        const imageUrl = data.message
        selectedBreed(imageUrl);
        };

    return (
      <div className="image-container">
        <img className="image-card" src={breed} alt="doggopicture" />
      </div>
    );
  
}

export default BreedImage;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There's some weird logic in here that doesn't make sense. breed is initialized to an empty string. Then, in your useEffect you have an empty dependencies array, which means it will be called once. Which means your API request hits https://dog.ceo/api/breed//images/random which presumably would fail (since breed was '').

Most likely you instead want:

import React, { useState, useEffect } from 'react';
import './breed-image.css';

function BreedImage () {
    const [breed, setBreed] = useState('');
    const [url, setUrl] = useState('');

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

    const fetchImage = async () => {
        const res = await fetch(`https://dog.ceo/api/breed/${breed}/images/random`)
        const data = await res.json();
        setUrl(data.message);
    };

    return (
    <>
      <DogPicker onChange={(breed) => setBreed(breed)} />
      <div className="image-container">
        <img className="image-card" src={url} alt="doggopicture" />
      </div>
    </>
    );
  
}

export default BreedImage;

where you'd pass setBreed to some other component. Or, you could pass breed down to this component as a prop, and again use useEffect to watch for changes.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!