Skip to content

Instantly share code, notes, and snippets.

@luisrudge
Created September 12, 2019 15:02
Show Gist options
  • Save luisrudge/63e4e56f9be6bd444c85336fc532896c to your computer and use it in GitHub Desktop.
Save luisrudge/63e4e56f9be6bd444c85336fc532896c to your computer and use it in GitHub Desktop.
api hooks
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>
);
};
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;
};
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