import { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { change_page, select_current_filters, select_current_sorting, select_current_page, } from "../features/todo/reducer"; import { refresh_todos } from "../refreshToDos"; import { get_nu_pages_function } from "../api/axios_methods"; function range(start, end) { return Array.from({ length: end - start + 1 }, (_, i) => i + start); } function render_pagination(current_page, nu_pages, handle_on_click) { const first_page = (
  • handle_on_click(1)}> «
  • ); const previous_page = (
  • handle_on_click(current_page - 1)} > <
  • ); const next_page = (
  • handle_on_click(current_page + 1)} > >
  • ); const last_page = (
  • handle_on_click(nu_pages)}> »
  • ); let in_between = <>; // If pages <= 5, render all of them. if (nu_pages <= 5) { in_between = ( <> {range(1, nu_pages).map((number) => (
  • handle_on_click(parseInt(e.target.innerText)) } > {number}
  • ))} ); } else if (current_page <= 3) { in_between = ( <> {range(1, 3).map((number) => (
  • handle_on_click(parseInt(e.target.innerText)) } > {number}
  • ))}
  • ...
  • handle_on_click(parseInt(e.target.innerText)) } > {nu_pages}
  • ); } else if (current_page >= nu_pages - 2) { in_between = ( <>
  • handle_on_click(1)}> 1
  • ...
  • {range(nu_pages - 2, nu_pages).map((number) => (
  • handle_on_click(parseInt(e.target.innerText)) } > {number}
  • ))} ); } else { in_between = ( <>
  • handle_on_click(1)}> 1
  • ...
  • {current_page}
  • ...
  • handle_on_click(nu_pages)} > {nu_pages}
  • ); } return ( ); } export function Pagination() { const [nu_pages, set_nu_pages] = useState(0); const nu_pages_api = get_nu_pages_function(); nu_pages_api((response) => set_nu_pages(response)); const dispatch = useDispatch(); const my_filters = useSelector(select_current_filters); const my_sorters = useSelector(select_current_sorting); const my_curr_page = useSelector(select_current_page); function handle_on_click(target) { if (my_curr_page == target) return; dispatch(change_page({ page: target })); refresh_todos(my_filters, my_sorters, my_curr_page, dispatch); } return (
    {render_pagination(my_curr_page, nu_pages, handle_on_click)}
    ); }