Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4011 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

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

const useFetchHelper = (url = '', defaultState = []) => {

    const [state, setState] = useState(defaultState);
    const [loading, setLoading] = useState(false);
    const dispatch = useDispatch()

    useEffect(() => {
        const dataFetch = async () => {
            setLoading(true);
            const { data: response } = await axios.get(url);
            const { success, data } = response

            if (!success) {
                typeof data === "string"
                    ? dispatch(addNotification({ style: "danger", msg: data }))
                    : dispatch(addNotification({ style: "danger", msg: 'Ha ocurrido un error' }))
                return
            }

            setState(data);
            setLoading(false);
        };

        dataFetch();
    }, [url]);

    return { data: state, loading };
}

export default useFetchHelper