Lightweight React hooks for API integration (Next.js/Node.js friendly).
Built by Alyvro → alyvro.com
useApi – Fetch data with caching, loading & error statesuseMutation – Handle POST/PUT/DELETE with optimistic updatesrefetch & invalidate – Control cached queriesnpm install @alyvro/api-hooks
# or
pnpm add @alyvro/api-hooks
# or
yarn add @alyvro/api-hooks
Wrap your app with the ApiContext.Provider to set a base URL and token handler.
import { ApiContext } from '@alyvro/api-hooks'
function MyApp({ Component, pageProps }) {
return (
<ApiContext.Provider
value={{
baseURL: '/api',
getToken: () => localStorage.getItem('token'),
}}
>
<Component {...pageProps} />
</ApiContext.Provider>
)
}
export default MyApp
import { useApi } from '@alyvro/api-hooks'
function Profile() {
const { data, loading, error, refetch } = useApi('/user/me')
if (loading) return <p>Loading...</p>
if (error) return <p>Error: {error.message}</p>
return (
<div>
<h1>{data.name}</h1>
<button onClick={refetch}>Refetch</button>
</div>
)
}
import { useMutation } from '@alyvro/api-hooks'
function UpdateUser() {
const { mutate, loading } = useMutation('/user/update', 'PUT', {
optimisticKey: '/user/me',
})
return (
<button
onClick={() => mutate({ name: 'Nima' }, { name: 'Nima (optimistic)' })}
disabled={loading}
>
Update
</button>
)
}
import { usePaginatedApi } from '@alyvro/api-hooks'
function UsersList() {
const { data, loading } = usePaginatedApi('/users', 1, 10)
if (loading) return <p>Loading...</p>
return (
<ul>
{data?.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
)
}
MIT © Alyvro