0

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

1
  • Very complicated implementation for just iterating posts. In 5 - 10 mins I will prepare something much simpler and will work :) Commented Nov 26, 2021 at 11:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No era la solucion que estaba buscando, sin embargo, me gusta mas esta forma que hiciste tu, se ve mas simple, manejable y rapida de hacer y procesar! TY
That's why StackOverflow exists. We should not just return the answer to your question. Many less experienced developers are asking the questions and they usually do not know that a better solution exists.
1
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.

Addition

After a closer look…you also have a race condition where you’re setting state using a callback (the one mentioned above) and then almost immediately setting state again in the loopThroughPosts function. That second time of setting the state is essentially keeping the value of count at 1, which can be seen by logging that value to the console. I would recommend splitting up the state like you originally had it to keep your updates to count and postsToShow separate from each other. If you have a definite reason to have the stage together your component will require some refactoring.

4 Comments

Just a side note…I prefer to keep pieces of state separate. I find it easier to read and maintain. This implementation above was much more common with class components, when that wasn’t really an option. There’s nothing wrong with splitting it up into multiple pieces of state, each using its own useState hook
It seems quite logical, but unfortunately it continues generating the same bug, and repeats the same three posts
Thanks for the update, just played with the sandbox a bit and added to the answer. If there’s a reason to keep the state combined I can take a look at some ways to refactor.
In the end I ended up transforming the component to the solution that @KrystianSztadhaus attached, but I really appreciate that you have taken the time to help me find the solution to the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.