You see, at this moment I am developing a showMorePost
that I had previously done successfully, but this time I reformulated it by joining all the states that I had in one with several arguments
const [state, setState] = useState({
postsToShow: [],
hover: false,
count: 1
});
const loopThroughPosts = (count) => {
for (
let i = count * postsPerPage - postsPerPage;
i < postsPerPage * count;
i
) {
if (posts[i] !== undefined) {
arrayForHoldingPosts.push(posts[i]);
}
}
setState({
...state,
postsToShow: arrayForHoldingPosts
});
};
// load the first set of posts when the page loads
// and then set the value of count to 2
useEffect(() => {
setState((prevState) => ({
...prevState,
count: prevState 1
}));
loopThroughPosts(state.count);
}, []);
const handleShowMorePosts = () => {
setState((prevState) => ({
...prevState,
count: prevState 1
}));
loopThroughPosts(state.count);
};
return (
<div>
<Posts postsToRender={state.postsToShow} />
<button
onClick={handleShowMorePosts}
onMouseEnter={() =>
setState({
...state,
hover: true
})
}
onm ouseLeave={() =>
setState({
...state,
hover: false
})
}
>
Load more
</button>
</div>
);
};
The problem is that now instead of bringing me the posts that follow when calling the handleShowMorePosts
, it generates an infinite loop in which, every time I call the function, it repeats the first three posts.
Here is the code: https://codesandbox.io/s/sad-dust-pybbe?file=/src/App.js:193-2128
CodePudding user response:
I hope that will help link. As a form of appreciation, please mark it as useful.
PS. I am not sure why do you need info about the hover, but I did not remove it.
CodePudding user response:
setState((prevState) => ({
...prevState,
count: prevState 1
}));
should be
setState((prevState) => ({
...prevState,
count: prevState.count 1
}));
As it’s currently written you’re adding prevState
(an object) to 1
(an integer) which is why you’re seeing some strange behavior.