1

I have made an API call in my react app, using hooks, redux and thunk and it works perfectly. I am able to display the data in my component.

However, the problem is that the array is too long - 249 objects inside it. I would like to split this array into chunks of 25 objects each and when the user reaches the bottom of the page, fetch the next 25 chunks and so on till the entire list is consumed.

Here's my approach so far:

const movies = useSelector((state: RootStateOrAny) => state.shows)
const searchResults = useSelector((state: RootStateOrAny) => state.shows);

useEffect(()=> {
    setLoading(true);
    dispatch(fetchAllShows());;
}, [dispatch])

var start, max, paginatedArr=[], pageSize = 25;

for(start = 0; max = movies.length, start < max; start += pageSize) {
    paginatedArr = movies.slice(start, start + pageSize);
}

This fetches 25 items from the movies array but it doesn't start from the first object. Please how do I rectify this and obtain the use-case I want? Thanks.

11
  • You need to have some kind of state that selects which page of the data you currently display. Then slice the data for that page, in a single call. No looping is necessary. Commented Jul 26, 2021 at 21:31
  • I have this function that splits the data into chunks of 25 each. It returns an array of arrays: Commented Jul 26, 2021 at 21:34
  • The issue is that I can't loop through it. I understand your perspective above but have no idea how to go about it Commented Jul 26, 2021 at 21:35
  • const res: any = []; // const splicedArray = function spliceMovies (arr: any, chunkSize: number) { function spliceMovies (arr: any, chunkSize: number) { while (arr.length > 0) { const chunk = arr.splice(0, chunkSize); res.push(chunk); } return res; } // console.log(splicedArray); console.log(spliceMovies(movies, 25)); Commented Jul 26, 2021 at 21:37
  • "It returns an array of arrays" - well, yes spliceMovies does, but the code in your question does not. It just repeatedly overwrite paginatedArr with an array, so it ends up with the last chunk from the loop. Commented Jul 26, 2021 at 21:39

0

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.