I have a code where the moment I open a page I am setting a List Array this way:
const [myArray, updateArray] = useState([]);
useEffect(() => {
var myItem= [...array1];
if (state.pageNumber == 1 myItem= [...array2];
else if (state.pageNumber == 2) myItem= [...array3];
updateArray(myItem);
}, []);
This works fine and the page is portraying the right array. The problem comes when I have to click a button and call the data on the updated array again. I have a function that when on click I have to read the array I updated. The problem is that "myArray" is coming up as blank. It only shows the data if the state changes for some reason like when I save my code again.
const handleSelect = (selectedIndex) => {
console.log(myArray);
};
Above comes blank even after it correctly updated and displays correctly on the page.
2
Answers
You could get the previous state and return it for the next state just by adding a callback.
If you want to set a new array everytime
pageNumber
changes, you should set thepageNumber
as theuseEffect
dependency.If you want to update the array everytime
array1
andarray2
changes, you should also add it to theuseEffect
dependency.Note: You should create a new copy of object or array every time you set a new state to re-render it.
Here is an example of pagination in React using Redux Toolkit. Your component should know how to access the items from the Redux store, along with the current page size and page index.
I exported the start index, end index, and page count calculation functions as well, since they will be needed outside of the pagination component.
Full demo here: Codesandbox
Package.json
Paginator.jsx
Usage