React hook to make api calls.
Minimal react hook to make api calls.
npm install use-api-call
yarn add use-api-call
// See examples on adavanced usage.
import React from "react";
import { useApiCall } from "use-api-call";
function App() {
const { data, error, loading, invoke } = useApiCall(
"https://api.github.com/users"
);
React.useEffect(() => {
invoke(); // You don't have to call invoke() if you pass option {invokeOnMount: true} to useApiCall()'s second argument. But, isn't it nice to have control when you trigger ajax call.
}, []);
if (loading) return <p>Loading...</p>;
return <div>{data}</div>;
}
useApiCall(request, [,options])
request
- Function | URL string - Any function that returns Promise
with data (or) A api url that returns JSON (uses fetch by default). (See the examples section).useApiCall(() => axios("/request/url/here").then(res => res.data))
options
- Object - Options object.
returns an object with {data, error, loading, invoke} values. See the Returns section for details.
updateOnlyIfMounted
true
invokeOnMount
useEffect(() => { invoke(); }, [])
.false
data
undefined
loading
error
undefined
invoke
Check test/index.test.tsx for all different examples. I’ll update some React examples soon.
// Manual invoke
const App = () => {
const { data, error, invoke, loading } = useApiCall(() =>
fetch("https://api.github.com/users").then((res: any) => res.json())
);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => invoke()}>Click</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
// Auto invoke on mount
const App = () => {
const { data, error, invoke, loading } = useApiCall(
() => fetch("https://api.github.com/users").then((res: any) => res.json()),
{
invokeOnMount: true,
}
);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
// Without ajax library. Uses fetch by default. You might have to polyfill for wide browser support.
const App = () => {
const { data, error, invoke, loading } = useApiCall(
"https://api.github.com/users",
{
invokeOnMount: true,
}
);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
// Pass arguments to axios.
const App = () => {
const { data, error, invoke, loading } = useApiCall(
(...args) => axios.get("https://api.github.com/users", ...args).then(res => res.data)
);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={() => invoke({headers: {Authorization: "Bearer 12345xcxcxc"}})}>Get Users</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};