| 1 |
import { debounce } from "lodash"; |
| 2 |
import { useSearchParams } from "react-router-dom"; |
| 3 |
|
| 4 |
export const usePaginationParams = () => { |
| 5 |
// get offset, limit, name filter from URL |
| 6 |
const [searchParams, setSearchParams] = useSearchParams(); |
| 7 |
const offset = parseInt(searchParams.get("offset", "0")) || 0; |
| 8 |
const limit = |
| 9 |
parseInt(searchParams.get("limit", "0")) || window.api_page_limit || 100; |
| 10 |
|
| 11 |
const _setOffset = (params, offset) => { |
| 12 |
if (offset < 0) offset = 0; |
| 13 |
if (offset === 0) { |
| 14 |
params.delete("offset"); |
| 15 |
} else { |
| 16 |
params.set("offset", offset); |
| 17 |
} |
| 18 |
}; |
| 19 |
const _setLimit = (params, limit) => { |
| 20 |
if (limit < 1) limit = 1; |
| 21 |
if (limit === window.api_page_limit) { |
| 22 |
params.delete("limit"); |
| 23 |
} else { |
| 24 |
params.set("limit", limit); |
| 25 |
} |
| 26 |
}; |
| 27 |
const setPagination = (pagination) => { |
| 28 |
// update pagination in one |
| 29 |
if (!pagination) { |
| 30 |
return; |
| 31 |
} |
| 32 |
setSearchParams((params) => { |
| 33 |
_setOffset(params, pagination.offset); |
| 34 |
_setLimit(params, pagination.limit); |
| 35 |
return params; |
| 36 |
}); |
| 37 |
}; |
| 38 |
|
| 39 |
const setOffset = (offset) => { |
| 40 |
if (offset < 0) offset = 0; |
| 41 |
setSearchParams((params) => { |
| 42 |
_setOffset(params, offset); |
| 43 |
return params; |
| 44 |
}); |
| 45 |
}; |
| 46 |
|
| 47 |
const setLimit = (limit) => { |
| 48 |
setSearchParams((params) => { |
| 49 |
_setLimit(params, limit); |
| 50 |
return params; |
| 51 |
}); |
| 52 |
}; |
| 53 |
|
| 54 |
const handleLimit = debounce(async (event) => { |
| 55 |
setLimit(event.target.value); |
| 56 |
}, 300); |
| 57 |
|
| 58 |
return { |
| 59 |
offset, |
| 60 |
setOffset, |
| 61 |
limit, |
| 62 |
setLimit, |
| 63 |
handleLimit, |
| 64 |
setPagination, |
| 65 |
}; |
| 66 |
}; |