I am a student trying to get the hang of React. So far I would like to be able to cut my data array that I receive from the API into chunks so that I can use a pagination effect later down the road. I cant figure out why the function arrayChunk() ends up causing too many renders. How can set my function to push the chunkedArray in to setChunkedYearArray? here is my full code:
import React, { useState, useEffect } from 'react';
import InformationBox from '../../component/InformationBox/InformationBox';
import arrowButton from '../../assets/arrow-button.svg';
const InformationBoxLayout = (props) => {
const [activeYear, setActiveYear] = useState([]);
const [chunkedYearArray, setChunkedYearArray] = useState([]);
useEffect(() => {
axios
.get('http://www.mocky.io/v2/5ea446a43000005900ce2ca3')
.then((response) =>
setActiveYear(
response.data.timelineInfo.filter((item) => item.year === '2018')
)
);
}, []);
const arrayChunk = (array, chunkSize) => {
const chunkedArray = [];
let clonedArray = [...array];
const splitPieces = Math.ceil(clonedArray.length / chunkSize);
for (let i = 0; i < splitPieces; i++) {
chunkedArray.push(clonedArray.splice(0, chunkSize));
}
setChunkedYearArray(chunkedArray);
};
return (
<div className={style.infoBoxLayoutStyle}>
<button className={style.leftArrow}>
<img src={arrowButton} alt='previous-page-button' />
</button>
{activeYear.length > 6
? arrayChunk(activeYear, 6)
: console.log('no split')}
<button className={style.rightArrow}>
<img
src={arrowButton}
alt='next-page-button'
className={style.rotateArrowRight}
/>
</button>
</div>
);
};
export default InformationBoxLayout;