I am trying to create a functionality where if a user clicks on a LOAD MORE
button, it returns more data.
I already have some code done but every time I click on the LOAD MORE
button, it removes the first 12 items and sets the new 12 items, but I don’t want that, I want to keep the 12 old tems, It is just a regular load more functionality.
JavaScript
x
30
30
1
const Comp = ({ data }) => {
2
const postsPerPage = 12
3
const [postsToShow, setPostsToShow] = useState([])
4
const [next, setNext] = useState(postsPerPage)
5
6
let arrayForHoldingPosts = []
7
8
const loopWithSlice = (start, end) => {
9
const slicedPosts = data.products.slice(start, end)
10
arrayForHoldingPosts = [arrayForHoldingPosts, slicedPosts]
11
setPostsToShow(arrayForHoldingPosts)
12
}
13
14
useEffect(() => {
15
loopWithSlice(0, postsPerPage)
16
}, [])
17
18
const handleShowMorePosts = () => {
19
loopWithSlice(next, next + postsPerPage)
20
setNext(next + postsPerPage)
21
}
22
23
return (
24
<div>
25
{postsToShow.map(p => <div></div>)}
26
<button onClick={handleShowMorePosts}>Load more</button>
27
</div>
28
)
29
}
30
Besides that, I need to turn this into a hook which I am going to using across the whole application.
What am I missing?
Any ideas?
Advertisement
Answer
You do not need an array arrayForHoldingPosts
instead just use
setPostsToShow( [...postsToShow, ...slicedPosts]);
arrayForHoldingPosts
is becoming empty array after every renders so old data is lost.
Hook example
JavaScript
1
37
37
1
const useLoadMore = (data, postsPerPage = 2) => {
2
const [postsToShow, setPostsToShow] = useState([]);
3
const [next, setNext] = useState(postsPerPage);
4
5
const loopWithSlice = (start, end) => {
6
const slicedPosts = data.slice(start, end);
7
setPostsToShow( [postsToShow, slicedPosts]);
8
};
9
10
useEffect(() => {
11
loopWithSlice(0, postsPerPage);
12
}, []);
13
14
15
const handleShowMorePosts = () => {
16
loopWithSlice(next, next + postsPerPage);
17
setNext(next + postsPerPage);
18
};
19
20
return { handleShowMorePosts, postsToShow }
21
22
}
23
24
25
const App = ({data}) => {
26
const {handleShowMorePosts, postsToShow } = useLoadMore(data)
27
28
return (
29
<div>
30
{postsToShow.map((p) => (
31
<div></div>
32
))}
33
<button onClick={handleShowMorePosts}>Load more</button>
34
</div>
35
);
36
};
37