0

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;

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.