i have used a custom-hook for pagination with material-ui. the component works fine for first page but call for next()
, prev()
and jump()
does not work.i have tried to pass next={next}
as props .i have read the api documentation from here but could not find proper way to call above functions.
here is code for usePagination.jsx custom-hooks
import React, { useState } from "react";
function usePagination(data, itemsPerPage) {
const [currentPage, setCurrentPage] = useState(1);
const maxPage = Math.ceil(data.length / itemsPerPage);
function currentData() {
const begin = (currentPage - 1) * itemsPerPage;
const end = begin + itemsPerPage;
return data.slice(begin, end);
}
function next() {
setCurrentPage((currentPage) => Math.min(currentPage + 1, maxPage));
}
function prev() {
setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
}
function jump(page) {
const pageNumber = Math.max(1, page);
setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
}
return {
next, prev, jump, currentData,
currentPage, maxPage
};
}
export default usePagination;
here is my Courses.jsx where i want to show list of courses with pagination.
import React, { useState, useEffect } from "react";
import {connect} from 'react-redux';
import CourseList from "./CourseList" ;
import usePagination from "./usePagination";
import * as actions from "../_actions/courseActions";
import CourseForm from "./CourseForm";
import { Grid, Paper, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, withStyles, ButtonGroup, Button } from "@material-ui/core";
import { useToasts } from "react-toast-notifications";
import { makeStyles } from '@material-ui/core/styles';
import Pagination from '@material-ui/lab/Pagination';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
marginTop: theme.spacing(2),
},
},
}));
const Courses =(props)=> {
const classes = useStyles();
useEffect(() => {
props.fetchAllCourses()
}, [])
// pagination code here
const { next, prev,
jump, currentData,
currentPage, maxPage }
=usePagination(props.courseList,4);
console.log("total pages:"+ maxPage)
return(
<div >
<CourseList
courseList={currentData()}
deleteCourse={props.deleteCourse}
createCourse={props.createCourse}
updateCourse={props.updateCourse}
/>
<div className={classes.root}>
<Pagination count={maxPage}
color="primary" />
</div>
</div>
);
}
const mapStateToProps= (state) =>({
courseList:state.course.list
})
const mapActionToProps={
fetchAllCourses:actions.fetchAll,
deleteCourse:actions.Delete,
createCourse:actions.create,
updateCourse:actions.update,
fetchCourse:actions.fetchById
}
export default connect(mapStateToProps,mapActionToProps)(Courses);
thanks in advance for help.