Created
September 12, 2019 15:02
-
-
Save luisrudge/63e4e56f9be6bd444c85336fc532896c to your computer and use it in GitHub Desktop.
api hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Products = () => { | |
const { loading, data: products, refetch } = useApiGET(`/products`); | |
const api = useApi(); | |
if (loading) { | |
return <Loading />; | |
} | |
return ( | |
<div> | |
{products.map(p => ( | |
<div key={p.id}> | |
<h1>{p.name}</h1> | |
<button onClick={async () => { | |
await api.delete(`/products/${p.id}`); | |
refetch(); | |
}}>Delete</button> | |
</div> | |
))} | |
</div> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef } from "react"; | |
import axios from "axios"; | |
export default () => { | |
const api = useRef( | |
axios.create({ | |
baseURL: `${process.env.REACT_APP_API_URL}` | |
}) | |
); | |
return api.current; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
import useApi from './useApi'; | |
export default path => { | |
const api = useApi(); | |
const [loading, setLoading] = useState(true); | |
const [data, setData] = useState(); | |
const [refetch, setRefetch] = useState(0); | |
useEffect(() => { | |
const getData = async () => { | |
setLoading(true); | |
const result = await api.get(path); | |
setData(result.data); | |
setLoading(false); | |
}; | |
getData(); | |
}, [path, api, refetch]); | |
return { data, loading, refetch: () => setRefetch(refetch + 1) }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment