UNPKG

dolab

Version:

Lightweight and fast React hooks library for fetching and managing data with Zustand state management. Ideal for scalable and modern React applications.

205 lines (136 loc) 6.33 kB
# بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ # 📦 Dolab ![Drawer GIF](https://media.tenor.com/JG9-sqzIMgQAAAAM/work-files-filing-cabinet.gif) ### 📊 Status & Stats ![npm](https://img.shields.io/npm/v/dolab?style=flat-square) [![dev.to](https://img.shields.io/badge/dev.to-%40abdoseadaa-black?style=flat-square&logo=dev.to)](https://dev.to/abdoseadaa) ![license](https://img.shields.io/npm/l/dolab?style=flat-square) **Dolab** (arabic word of Drawer) is a lightweight and fast React hooks library for fetching and managing data using Zustand under the hood. It simplifies the process of managing remote data fetching and sharing it across your React application efficiently. ## 🚀 Features - ✅ Simple React hook API - 🔁 Auto refetching with dependency array - 🧠 Shared global store powered by Zustand - 💡 TypeScript support - ⏳ Optional data lifetime handling ## 📦 Installation ```bash npm install dolab ``` ## 🧪 Example ### Hook & Component Setup ```tsx // useTodos.ts import { SetDolabData, useDolab, useDolabData } from "dolab"; type Todo = { userId: number; id: number; title: string; completed: boolean; }; const fetchTodos = async (setData: SetDolabData<Todo[]>) => { const response = await fetch("https://jsonplaceholder.typicode.com/todos"); const json = await response.json(); setData(json); }; const id = "todos"; export default function useTodos() { return useDolab<Todo[]>({ id: id, fetch : fetchTodos, }); } export function useTodosData() { return useDolabData<Todo[]>({ id: id }); } ``` ```tsx // Todos.tsx import useTodos from "./useTodos"; export default function Todos() { const { data, loading, triggerRefetch: refetch } = useTodos(); if (!data) { return ( <button onClick={refetch}>{loading ? "Loading..." : "Load data"}</button> ); } return ( <div> {data.map((todo) => ( <div key={todo.id}> <p>{todo.userId}</p> <p>{todo.title}</p> <p>{todo.completed.toString()}</p> </div> ))} </div> ); } ``` ### 🛠️ Using Dolab Directly Without Custom Hooks You can use `useDolab` directly inside your component without creating a separate custom hook: ```tsx import { SetDolabData , useDolab } from "dolab"; type Todo = { userId: number; id: number; title: string; completed: boolean; }; const fetchTodos = async (setData: SetDolabData<Todo[]>) => { const response = await fetch("https://jsonplaceholder.typicode.com/todos"); const data = await response.json(); setData(data); }; export default function Todos() { const { data : todos, loading, triggerRefetch: refetch } = useDolab<Todo[]>({ id: "todos", fetch : fetchTodos, }); if (!todos) { return ( <button onClick={refetch}>{loading ? "Loading..." : "Load todos"}</button> ); } return ( <div> {todos.map((todo) => ( <div key={todo.id}>{todo.title}</div> ))} </div> ); } ``` --- ### 📌 Difference Between `useTodos` and `useTodosData` - `useTodos` This hook **calls the API** and saves the result to the Dolab store. It takes care of data fetching logic and must be called **before** `useTodosData` to ensure the data is available in the store. - `useTodosData` This hook **reads data from the Dolab store** and does not trigger the API call itself. It’s a lightweight hook useful for accessing shared data already fetched via `useTodos`. #### 🧠 Additional Options in `useDolab` - `deps?: any[]` An optional dependency array. The API will automatically be called **again** if any value inside `deps` changes. Useful when the data depends on external variables (e.g. filters or search terms). - `lifeTime?: number` Optional. Defines how long the data stays in the store before being cleared to free up memory. If not provided, Dolab uses the default: ### 🔧 Parameters The following parameters are required or optional when using the hook: | 🏷️ Property | 🧩 Type | ✅ Required | 🕒 Default | 📖 Description | |--------------|-----------------------------------------------------------|-------------|----------------|-----------------------------------------------------| | `id` | `string` | Yes | — | Unique identifier. | | `fetch` | `(setData: SetDolabData<T>, ...args: any) => Promise<void>` | Yes | — | Async function to fetch and set data. | | `lifeTime` | `number` | No | `1800000` | Lifetime in milliseconds (default: 30 minutes). | | `deps` | `any[]` | No | `[]` | Dependencies array for reactivity. | ### 🔁 Return Values The hook returns the following properties to manage and interact with the fetched data: | 🏷️ Property | 🧩 Type | 📖 Description | |--------------------|------------------|--------------------------------------------------------------------------------| | `data` | `T \| undefined` | 📦 The data returned from the Dolab after being fetched and stored. Initially `undefined`. | | `loading` | `boolean` | ⏳ Indicates whether the data is currently being fetched (loading state). | | `triggerRefetch` | `() => void` | 🔄 Manually triggers a re-fetch, useful for events like clicks or submissions. | ### 🧪 Live Demo (CodeSandbox) [![Edit Dolab Sandbox](https://codesandbox.io/api/v1/sandboxes/t3f9yl/screenshot.png)](https://codesandbox.io/p/devbox/t3f9yl) Try it live on [CodeSandbox](https://codesandbox.io/p/devbox/t3f9yl) ## 🚀 About Me I love coding ¯\_( ͡° ͜ʖ ͡°)\_/¯ ## Authors - [X](https://x.com/abdoseadaa) - [linkedin](https://www.linkedin.com/in/abdoseadaa/) ﴾ ذَٰلِكَ فَضْلُ اللَّهِ يُؤْتِيهِ مَن يَشَاءُ ۚ وَاللَّهُ ذُو الْفَضْلِ الْعَظِيمِ﴿