Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
15312 stevensc 1
import axios from 'axios'
2
import { useEffect } from 'react'
3
import { useState } from 'react'
4
import { useDispatch } from 'react-redux'
5
import { addNotification } from '../../redux/notification/notification.actions'
6
 
7
const useGetDataTable = ({
8
	url = '',
9
	params = {
10
		search: '',
11
		length: 10,
12
		start: 1
13
	}
14
}) => {
15
 
16
	const dispatch = useDispatch()
17
	const [items, setItems] = useState([])
18
	const [total, setTotal] = useState(0)
19
	const [lastPage, setLastPage] = useState(0)
20
	const [startItem, setStartItem] = useState(0)
21
	const [lastItem, setLastItem] = useState(0)
22
 
23
	const getDataTable = () => {
24
		axios.get(url, { params: { ...params } })
25
			.then(({ data: resData }) => {
26
				const { success, data } = resData
27
 
28
				if (!success) {
29
					dispatch(addNotification({
30
						style: 'danger',
31
						msg: 'Ha ocurrido un error'
32
					}))
33
				}
34
 
35
				setItems(data.items)
36
				setTotal(data.total)
37
				setLastPage(Math.ceil(data.total / data.items.length))
38
			})
39
			.catch(() => dispatch(addNotification({ style: 'danger', msg: 'Ha ocurrido un error' })))
40
	}
41
 
42
	useEffect(() => getDataTable(), [params])
43
 
44
	useEffect(() => {
45
		if (params.start > 1) {
46
			setStartItem((params.length * (params.start - 1)) + 1)
47
			return
48
		}
49
		setStartItem(1)
50
	}, [params.start])
51
 
52
	useEffect(() => {
53
		if (items && startItem > 1) {
54
			setLastItem(startItem + (items.length - 1))
55
			return
56
		}
57
		if (items && startItem <= 1) {
58
			setLastItem(items.length)
59
			return
60
		}
61
	}, [items])
62
 
63
	return { items, total, lastPage, startItem, lastItem }
64
}
65
 
66
export default useGetDataTable