Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created July 15, 2020 16:34
Show Gist options
  • Save brunoksato/9acde360442fb301c4c0b5ed443106f8 to your computer and use it in GitHub Desktop.
Save brunoksato/9acde360442fb301c4c0b5ed443106f8 to your computer and use it in GitHub Desktop.
hooks + axios + react
import api from "./util/api";
export const list = () => api.get("/users");
export const userService = {
list,
};
import { create } from "apisauce";
const api = create({
baseURL: `${process.env.REACT_APP_BASE_URL}`,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
timeout: 20000,
});
api.addRequestTransform((request) => {
console.log(request);
});
api.addResponseTransform((response) => {
console.log(response);
});
export default api;
import { ApiResponse } from "apisauce";
import { useEffect, useState } from "react";
interface Output {
data: Array<Object> | Object | string | any;
loading: boolean;
error: boolean;
}
const useDataApi = (
promise: Function,
initialData: Array<Object> | Object | any,
options?: Object
): Output => {
const [data, setData] = useState(initialData);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setError(false);
setLoading(true);
const response = (await promise(options)) as ApiResponse<any>;
if (response.ok) {
setLoading(false);
setData(response.data);
return;
}
setData(response.problem);
setError(true);
setLoading(false);
};
fetchData();
}, [promise]);
return { data, loading, error };
};
export default useDataApi;
import useDataApi from "../../hooks/useDataApi";
import { userService } from "./api/action";
const UsersList = () => {
const { data, loading, error } = useDataApi(userService.list, []);
if (loading) {
return (
<>
<p>Loading...</p>
</>
);
}
if (!loading && error) {
return (
<>
<p>{data}</p>
</>
);
}
return (
{!loading && data?.length > 0 ? (list here) : (empty state)
)
}
export default UsersList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment