Home > other >  React: How to build a gallery of 6 random images
React: How to build a gallery of 6 random images

Time:08-26

I am going to create a react app that will present a gallery of 6 random dog images from enter image description here

CodePudding user response:

You need to do 6 requests. The best practice would be to request those all at the same time and await them together. Something like this:

const dogRequests = new Array(6)
    .fill("https://random.dog/woof.json")
    .map((url)=> fetch(url).then((resp)=> resp.json()))


const dogs = await Promise.all(dogRequests)
console.log(dogs)

In a React component you could do something like this (unfortunately the api also returns videos, you would need to catch that):

import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default function App() {
  const [dogImages, setDogImages] = React.useState([]);

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const dogRequests = new Array(6)
          .fill('https://random.dog/woof.json')
          .map((url) =>
            fetch(url)
              .then((resp) => resp.json())
              .then((dogObject) => dogObject.url)
          );

        const dogs = await Promise.all(dogRequests);
        setDogImages(dogs);
      } catch (error) {
        console.log('error', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {dogImages.map((dogImage) => (
        <div>
          <img src={dogImage} />
        </div>
      ))}
    </div>
  );
}

CodePudding user response:

If you are happy to call it 6 times, then basically re-clone the useEffect() function.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  const [dogImg, setDogImg] = useState(null);
  const [dogImg2, setDogImg2] = useState(null);
  useEffect(() => {
    const url = "https://random.dog/woof.json";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
        setDogImg(json.url);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    const url = "https://random.dog/woof.json";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
        setDogImg2(json.url);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <div>
        <img src={dogImg} alt="dog1" />
      </div>
      <div>
        <img src={dogImg2} alt="dog2" />
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodePudding user response:

Your api endpoint seems to return only one image at the time. So for your need you would end up calling it 6 times when the app load and then 6 times on each click on "Next". Not super nice.

I would advise to either use another API that can return the wanted number of random images : https://dog.ceo/api/breeds/image/random/6

Or using your api you can call /doggos that return a lot of images. Then you can just make array out of it to fit your needs.

https://random.dog/doggos

  • Related