Created
March 3, 2020 07:39
-
-
Save MRezaSafari/db822aaf4afdae913eb24b54d869d393 to your computer and use it in GitHub Desktop.
useTable hook for ant design 4.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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