use-octokit
v0.0.4
Published
A fully-typed data-fetching hook for the Github API. Built on top of Octokit] and SWR. Use this hook inside a React component for a type-safe, data-fetching experience with caching, polling, and more.
Downloads
5
Maintainers
Readme
🐙 use-octokit
A fully-typed data-fetching hook for the Github API. Built on top of Octokit and SWR.
Use this hook inside a React component for a type-safe, data-fetching experience with caching, polling, and more.
💡 Checkout an example of
use-octokit
inside a Next.js app.
📡 Install
npm install use-octokit
yarn add use-octokit
pnpm add use-octokit
👋 Hello there! Follow me @linesofcode or visit linesofcode.dev for more cool projects like this one.
🚀 Getting Started
After you've obtained a github auth token, you can use the useOctokit
hook to fetch data from the Github API.
The function inputs and outputs are all type-safe and the auto-complete in your IDE should kick-in to list all the available GitHub API endpoints and parameters.
You can also use the OctokitProvider
to set the auth token for all the useOctokit
calls in your app. It also accepts an octokit instance if you want to use your own.
Conditional fetching is supported by passing undefined
as the first argument to useOctokit
or by omitting the auth
config.
Remember this is an SWR hook, so you can use all the SWR config options to customize the fetching behavior or nest it within your own SWR providers.
React hook example
import { useOctokit } from 'use-octokit';
// call the hook inside a React component
const user = useOctokit('users', 'getAuthenticated', undefined, {
auth: session.data?.user?.accessToken,
});
// The above is fully-typed SWR response object with the data, error and isLoading properties.
// user.isLoading
// user.data.avatar_url
const [page, setPage] = useState(0);
const repos = useOctokit(
'search',
'repos',
{
sort: 'updated',
q: 'nextjs',
page,
},
{
auth: session.data?.user?.accessToken,
},
{
refreshInterval: page === 0 ? 1000 * 10 : 0,
}
);
// The final argument is an optional SWR config object, in the example above the repos will be refetched every 10 seconds on the first page.
// repos.isLoading
// repos.data.items[0].full_name
if (repos.isLoading || user.isLoading) {
return <div>Loading...</div>;
}
React context provider example
import { OctokitProvider } from 'use-octokit';
// inside a React component render method
// pass an auth token to the provider to use it for all the useOctokit calls in your app
return (
<OctokitProvider auth={session.data?.user?.accessToken}>
{children}
</OctokitProvider>
);
😅 Do you have problems consistently typing "octokit" without typos like I do? All the exports have a "github" alias, so you can use
useGithub
instead ofuseOctokit
if you need.