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:
JavaScript
x
46
46
1
import React from "react";
2
import { useState, useEffect } from 'react';
3
import Grid from "./components/elements/Grid";
4
import PetImage from "./components/elements/PetImage";
5
import LoadMore from "./components/elements/LoadMore";
6
7
const Main = () => {
8
9
//state for img grid
10
const [pets, setPets] = useState([]);
11
12
//load more pets
13
//need to write a condtion allow more pets
14
const loadMorePets = () => {
15
?code?
16
};
17
18
//fake api call
19
useEffect(()=>{
20
fetch('./petfinder.json')
21
.then((res)=>res.json())
22
.then((data)=>{
23
// console.log(data); //test
24
setPets(data.slice(0, 9))
25
});
26
},[])
27
28
return (
29
<div>
30
<Grid text="Find your pet!" >
31
{pets.map( (pet, id) => (
32
<PetImage
33
key={id}
34
pet={pet}
35
petId={pet.id}
36
clickable
37
/>))}
38
</Grid>
39
<LoadMore text="Load More" onClick={loadMorePets} />
40
</div>
41
);
42
};
43
44
export default Main;
45
```THANKS!
46
Advertisement
Answer
So you already have all the data but you need to dispaly it in pieces? How about this.
JavaScript
1
46
46
1
import React from "react";
2
import { useState, useEffect } from 'react';
3
import Grid from "./components/elements/Grid";
4
import PetImage from "./components/elements/PetImage";
5
import LoadMore from "./components/elements/LoadMore";
6
7
const Main = () => {
8
9
//state for img grid
10
const [allPets, setAllPets] = useState([]);
11
const [petCount, setPetCount] = useState(9);
12
13
//load more pets
14
//need to write a condtion allow more pets
15
const loadMorePets = () => {
16
setPetCount(allPets.length)
17
};
18
19
//fake api call
20
useEffect(()=>{
21
fetch('./petfinder.json')
22
.then((res)=>res.json())
23
.then((data)=>{
24
// console.log(data); //test
25
setAllPets(data)
26
});
27
},[])
28
29
return (
30
<div>
31
<Grid text="Find your pet!" >
32
{allPets.slice(0, petCount).map( (pet, id) => (
33
<PetImage
34
key={id}
35
pet={pet}
36
petId={pet.id}
37
clickable
38
/>))}
39
</Grid>
40
<LoadMore text="Load More" onClick={loadMorePets} />
41
</div>
42
);
43
};
44
45
export default Main;
46