Skip to content
Advertisement

How can I use the prevState in a state with multiple arguments?

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
          })
        }
        onMouseLeave={() =>
          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

Advertisement

Answer

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.

Advertisement