Skip to content

Instantly share code, notes, and snippets.

@popehiflo
Last active April 1, 2020 13:45
Show Gist options
  • Save popehiflo/bcaabc19bd6ce025d936f3c3f5242a7b to your computer and use it in GitHub Desktop.
Save popehiflo/bcaabc19bd6ce025d936f3c3f5242a7b to your computer and use it in GitHub Desktop.
Custom Hook permite extraer logica para una llamada a API
import {useState,useEffect} from "react"
function useFetch(url, initialState, options) {
// data: donde llega la info
// loading: saber si esta cargando la data
// error: el tipo de error
const [data, setData] = useState(initialState)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
function getData() {
setLoading(true)
fetch(url) //options aqui para decirle el tipo de metodo que recibe
.then(response => response.json())
.then(response => {
setData(response)
setLoading(false)
}
)
.catch(error => {
setLoading(false)
setError(error)
})
}
useEffect(() => {
getData()
}, [])
return {
data,
loading,
error
}
}
export default useFetch
//En App.js
import React from 'react';
import useFetch from './CustomHooks/useFetch';
function App() {
const users = useFetch('https://jsonplaceholder.typicode.com/users', [])
const posts = useFetch('https://jsonplaceholder.typicode.com/posts',[])
return (
<div className="data">
<h2>Users</h2>
<ul>
{users.loading && <p>Cargando..</p>}
{users.data && users.data.map(user => (
<li key={user.id}>{user.name} - {user.username}</li>
))}
</ul>
<br />
<h2>Posts</h2>
<ul>
{posts.loading && <p>Cargando..</p>}
{posts.data && posts.data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment