Skip to content

Instantly share code, notes, and snippets.

@MRezaSafari
Created March 3, 2020 07:39
Show Gist options
  • Save MRezaSafari/db822aaf4afdae913eb24b54d869d393 to your computer and use it in GitHub Desktop.
Save MRezaSafari/db822aaf4afdae913eb24b54d869d393 to your computer and use it in GitHub Desktop.
useTable hook for ant design 4.x
import axios from 'axios';
import React from 'react';
const useTable = (url, initialParams) => {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const [filters, setFilters] = React.useState({});
const [pagination, setPagination] = React.useState({
pageSizeOptions: ['5', '10', '20', '30', '100'],
defaultPageSize: 5,
showSizeChanger: true,
showTotal: total => <span>تعداد کل : {total}</span>
});
const fetch = React.useCallback(
async params => {
setLoading(true);
const req = await axios.get('products', {
params: {
...initialParams,
...params,
...filters
}
});
const nextPagination = { ...pagination };
//you might change this to whatever suits you
nextPagination.total = req.data.total;
setLoading(false);
setData(req.data.data);
setPagination(nextPagination);
},
[pagination, url, initialParams]
);
const pageChangeHandler = pagination => {
const pager = { ...pagination };
pager.current = pagination.current;
setPagination(pager);
fetch({
limit: pagination.pageSize,
offset: pagination.current
});
};
const filterChangeHandler = filters => {
setFilters(filters);
};
React.useEffect(() => {
fetch();
}, [filters]);
return { data, loading, pagination, pageChangeHandler, filterChangeHandler };
};
export default useTable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment