Skip to content
Advertisement

How to write a hook to load more button from fetching a json?

I am calling my fake api using fetch and getting Json data. How can I wire up my load more button so that it it loads more data?

Everything works, I just need to add functionality to that load button. I have an empyt function…

See code below:

import React from "react";
import { useState, useEffect } from 'react';
import Grid from "./components/elements/Grid";
import PetImage from "./components/elements/PetImage";
import LoadMore from "./components/elements/LoadMore";

const Main = () => {

    //state for img grid
    const [pets, setPets] = useState([]);
  
    //load more pets
    //need to write a condtion allow more pets
    const loadMorePets = () => {
      ?code?
    };

    //fake api call
    useEffect(()=>{
        fetch('./petfinder.json')
          .then((res)=>res.json())
          .then((data)=>{
            // console.log(data); //test
            setPets(data.slice(0, 9))
          });
      },[])

  return (
    <div>
      <Grid text="Find your pet!" >
          {pets.map( (pet, id) => (
          <PetImage
            key={id} 
            pet={pet}
            petId={pet.id}
            clickable
          />))}
      </Grid>
      <LoadMore text="Load More" onClick={loadMorePets} />
    </div>
  );
};

export default Main;
```THANKS!

Advertisement

Answer

So you already have all the data but you need to dispaly it in pieces? How about this.

import React from "react";
import { useState, useEffect } from 'react';
import Grid from "./components/elements/Grid";
import PetImage from "./components/elements/PetImage";
import LoadMore from "./components/elements/LoadMore";

const Main = () => {

    //state for img grid
    const [allPets, setAllPets] = useState([]);
    const [petCount, setPetCount] = useState(9);
  
    //load more pets
    //need to write a condtion allow more pets
    const loadMorePets = () => {
      setPetCount(allPets.length)
    };

    //fake api call
    useEffect(()=>{
        fetch('./petfinder.json')
          .then((res)=>res.json())
          .then((data)=>{
            // console.log(data); //test
            setAllPets(data)
          });
      },[])

  return (
    <div>
      <Grid text="Find your pet!" >
          {allPets.slice(0, petCount).map( (pet, id) => (
          <PetImage
            key={id} 
            pet={pet}
            petId={pet.id}
            clickable
          />))}
      </Grid>
      <LoadMore text="Load More" onClick={loadMorePets} />
    </div>
  );
};

export default Main;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement