Show image with path from an API in ReactJs

Viewed 324

i get data from an API and i want to display the picture via a path that the api give to me

I have this simple code to get a random actor, And i have all of his information save as a json such as this data : profile_path: "/j2Yahha9C0zN5DRaTDzYA7WtdOT.jpg"

How can i use this path to show the picture with<img src="??"/>


function Game() {
  const [page, setPage] = useState(1);
  const [apiResponse, setApiResponse] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const API_KEY_MOVIE_DB = 'xxxxxxxxxxxxxxxxx';

  useEffect(() => {
    const myInit = {
        method: "GET",
        mode: "cors",
      };
      const random_0_20 = parseInt(Math.random() * (200 - 1) + 1);
      const actor = fetch(`https://api.themoviedb.org/3/person/${random_0_20}?api_key=${API_KEY_MOVIE_DB}`, myInit)
      .then(res => res.json())
      .then(response => {
        setApiResponse(JSON.stringify(response));
        setIsLoading(false);
        localStorage.setItem(`${random_0_20}`, JSON.stringify(response))
      })
      .catch(error => console.log(error));
    }, [page]);

  return (
    <div>
        {isLoading && <p>Loading</p>}
        {apiResponse}
        <img src={apiResponse.profile_path}></img>
    </div>
  );
} ```
1 Answers

You're setting the state to a string:

setApiResponse(JSON.stringify(response))

And a string has no property called profile_path:

<img src={apiResponse.profile_path}></img>

If the result from the API is an object, just set the state to that object:

setApiResponse(response)

You should also initialize the state to an object, rather than an array:

const [apiResponse, setApiResponse] = useState({});

Possibly even with the property set to a default value, to avoid "undefined" rendering in the markup:

const [apiResponse, setApiResponse] = useState({ profile_path: '' });

Strings, objects, and arrays are all very different things. Keep the types of your variables consistent so the behavior of the code remains consistent.

Related