Proyectos de Subversion LeadersLinked - Backend

Rev

Autoría | Ultima modificación | Ver Log |

import axios from 'axios'
import { useEffect } from 'react'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addNotification } from '../../redux/notification/notification.actions'

const useGetDataTable = ({
        url = '',
        params = {
                search: '',
                length: 10,
                start: 1
        }
}) => {

        const dispatch = useDispatch()
        const [items, setItems] = useState([])
        const [total, setTotal] = useState(0)
        const [lastPage, setLastPage] = useState(0)
        const [startItem, setStartItem] = useState(0)
        const [lastItem, setLastItem] = useState(0)

        const getDataTable = () => {
                axios.get(url, { params: { ...params } })
                        .then(({ data: resData }) => {
                                const { success, data } = resData

                                if (!success) {
                                        dispatch(addNotification({
                                                style: 'danger',
                                                msg: 'Ha ocurrido un error'
                                        }))
                                }

                                setItems(data.items)
                                setTotal(data.total)
                                setLastPage(Math.ceil(data.total / data.items.length))
                        })
                        .catch(() => dispatch(addNotification({ style: 'danger', msg: 'Ha ocurrido un error' })))
        }

        useEffect(() => getDataTable(), [params])

        useEffect(() => {
                if (params.start > 1) {
                        setStartItem((params.length * (params.start - 1)) + 1)
                        return
                }
                setStartItem(1)
        }, [params.start])

        useEffect(() => {
                if (items && startItem > 1) {
                        setLastItem(startItem + (items.length - 1))
                        return
                }
                if (items && startItem <= 1) {
                        setLastItem(items.length)
                        return
                }
        }, [items])

        return { items, total, lastPage, startItem, lastItem }
}

export default useGetDataTable