1.35.0 • Published 7 months ago
grabbr v1.35.0
Grabber
Grabber is a JavaScript data-fetching utility that supports automatic caching, time-based revalidation, Server-Side Rendering (SSR), and React Query integration. It allows developers to fetch data with ease while ensuring that resources are cached and revalidated periodically.
Features
- Automatic Caching: Caches the fetched data and uses it until the cache expires.
- Time-Based Revalidation: Automatically re-fetches data after a specified period.
- SSR Support: Supports Server-Side Rendering (SSR) in frameworks like Next.js.
- React Query Integration: Easily integrates with React Query for caching and revalidation support.
Installation
Install the Grabber package via npm:
npm install grabbr
Usage
Client-Side Usage
Import and use the grab function for fetching data with revalidation.
import grab from 'grabber';
async function fetchData() {
const data = await grab('/api/data', 6000); // Revalidate every 6000ms
console.log(data);
}
Or you can use grab with options for full control of the grab
async function getPosts() {
const headers = {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'application/json',
};
const body = {
JSON.stringify({
username: 'example_user',
message: 'Hello, world!',
});
}
const data = await grab('api/posts', 60000, {
"method": 'GET',
headers,
body
});
}
SSR support with next.js
Grab supports SSR in next.js
import { grabSSR } from 'grabber';
export async function getServerSideProps() {
const data = await grabSSR('/api/data', 6000); // Revalidate every 6000ms
return {
props: { data },
};
}
export default function MyPage({ data }) {
return (
<div>
<h1>SSR Data Fetching</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
React Query
You can use grabber with react query also
// Example component using grab with React Query
export function MyComponent() {
const { data, error, isLoading } = useGrabQuery('/api/data', 6000); // Revalidate every 6 seconds
if (isLoading) {
return <div>Loading...</div>;
} else if (error instanceof Error) {
return <div>Error: {error.message}</div>;
} else {
return (
<div>
<h1>Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
}
// Wrap your application with the QueryClientProvider
function App() {
return (
<QueryClientProvider client={queryClient}>
<MyComponent />
</QueryClientProvider>
);
}
export default App;