Educación online efectiva

Aprende con expertos de la industria

COMPARTE ESTE ARTÍCULO Y MUESTRA LO QUE APRENDISTE

Que tal si hacemos un hook para cualquier llamado fetch api?
Ademas, lo vamos a hacer con manejo de errores y loading

/src/hooks/fetchApiHook.js

// /fetchApiHook.js

import { useState, useEffect } from 'react';

export const useFetchData = (BASE_URL = '', error_msg = 'An error has ocurred getting the data') => {
    const [fetch_data, setFetchData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            //Pedimos los datos a la api
						try {
                const response = await window.fetch(BASE_URL);
                if (!response.ok) {
                    throw new Error(`Http status ${response.status}`);
                }
                const data = await response.json();
                console.log(data);
                setFetchData(data.results);
            } catch (error) {
//Si hay un error ...
                console.error(error.message);
                setError(error_msg)
            }
            setLoading(false);
        }
        fetchData();
    }, [BASE_URL]); //Hacer enfasis en la url
//Retornamos nuestro fetch_data como data, nuestro loading y error
    return { data: fetch_data, loading, error };
}

Ahora en el componente al cual queremos aplicar nuestro Custom Hook

import React  from "react";
//Impotamos nuestro custom hook
import { useFetchData } from "../hooks/useFetchData";
export const Component = () => { 
	const BASE_URL = 'aqui el url de su api';
	const { data, loading, error } = useFetchData(BASE_URL); // Guardamos las variables que nos retorna nuestro custom hook, pasanadole como parametro la url de la api, el mensaje del error es opcional
	if (loading) return "Loading ...";
	if (error) return `Error ${error}`;
	return(
	//Un ejemplo de como mostrar los datos
		{data.map((element) => (
         		 <p key={element.id}>{element.name}</p>
        	))}
         	
	)
}

No olvides dejar tus dudas y aportes
Buena suerte

Educación online efectiva

Aprende con expertos de la industria

COMPARTE ESTE ARTÍCULO Y MUESTRA LO QUE APRENDISTE

0 Comentarios

para escribir tu comentario

Artículos relacionados