Home > other >  How to get images to load in multiple <img> after the call from api
How to get images to load in multiple <img> after the call from api

Time:04-29

I am trying to load 12 random images using thecatapi, i have managed to wirte the code that fetches the image, but i am only getting one random imagen in all the

i do not know how to iterate and pass the results in react

could someone please help me?

my code below

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

// Style Images
import '../index.css';


// Fetch data from
const url = 'https://api.thecatapi.com/v1/images/search?limit=10';

function ImageGrid() {

// primary state is catUrl, hook updates to setCatUrl when called
const [ catUrl, setCatUrl ] = 
    useState('https://cdn2.thecatapi.com/images/aat.jpg');

    useEffect(() => {
        console.log('Loading your feline friends....');
        getCat();
    }, []);


// The Function to fetch images
const getCat = () => {
    console.log('Hello World')

    // fetch http request
    fetch(url)
        .then((res) => res.json()) //gives data in json
        .then((cats) => {
            console.log('Cats: ', cats);

            // Fetch Cat data primary state
            const catUrl = cats[0].url;
            // update state with new url value
            setCatUrl(catUrl);
        })
        .catch((error) => {
            console.log('Error: ', error);
        });
}


return (

    <>
        <h1>Look At These Beautiful Kiity's!</h1>
        <img src={catUrl} alt="" />
        <img src={catUrl} alt="" />
        <img src={catUrl[2]} alt="" />
        <img src={catUrl[3]} alt="" />
        <img src={catUrl[4]} alt="" />
        <img src={catUrl[5]} alt="" />
        <img src={catUrl[6]} alt="" />
        <img src={catUrl[7]} alt="" />
        <img src={catUrl[8]} alt="" />
        <img src={catUrl[9]} alt="" />
        <img src={catUrl[10]} alt="" />
        <img src={catUrl[11]} alt="" />
        <button onClick={getCat}>Refresh</button>
    </>

) }

export default ImageGrid

CodePudding user response:

Try to Run this. Is this how you want to display data?

import React, { useState, useEffect } from "react";

// Style Images

// Fetch data from
const url = "https://api.thecatapi.com/v1/images/search?limit=10";

export default function ImageGrid() {
  // primary state is catUrl, hook updates to setCatUrl when called
  const [catUrl, setCatUrl] = useState([]);

  useEffect(() => {
    console.log("Loading your feline friends....");
    getCat();
  }, []);

  // The Function to fetch images
  const getCat = () => {
    console.log("Hello World");

    // fetch http request
    fetch(url)
      .then((res) => res.json()) //gives data in json
      .then((cats) => {
        console.log("Cats: ", cats);

        // Fetch Cat data primary state
        const catUrl = cats.map(cat=>cat.url);
        // update state with new url value
        setCatUrl(catUrl);
      })
      .catch((error) => {
        console.log("Error: ", error);
      });
  };

  return (
    <>
      <h1>Look At These Beautiful Kiity's!</h1>

      {catUrl.length > 0 && catUrl.map((url) => <img src={url} />)}
      <button onClick={getCat}>Refresh</button>
    </>
  );
}




CodePudding user response:

check out this codesandbox (very brief): https://codesandbox.io/s/admiring-breeze-6wyfui?file=/src/ImageGrid.js

  • Related