{"id":19290407,"url":"https://github.com/deve-sh/usefetch","last_synced_at":"2025-02-23T23:46:08.893Z","repository":{"id":118849106,"uuid":"543231290","full_name":"deve-sh/useFetch","owner":"deve-sh","description":"A Simple hook-based fetcher and caching implementation for React, inspired by SWR","archived":false,"fork":false,"pushed_at":"2023-01-11T15:29:05.000Z","size":346,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-05T19:43:01.439Z","etag":null,"topics":["data-fetching","fetch","react","react-hooks","swr","usefetch"],"latest_commit_sha":null,"homepage":"https://blog.devesh.tech/post/creating-our-own-swr","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deve-sh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-09-29T16:58:46.000Z","updated_at":"2023-03-07T07:39:27.000Z","dependencies_parsed_at":null,"dependency_job_id":"f1f8e0a3-887f-4e30-afb4-556e42d5affc","html_url":"https://github.com/deve-sh/useFetch","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deve-sh%2FuseFetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deve-sh%2FuseFetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deve-sh%2FuseFetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deve-sh%2FuseFetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deve-sh","download_url":"https://codeload.github.com/deve-sh/useFetch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240395742,"owners_count":19794573,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-fetching","fetch","react","react-hooks","swr","usefetch"],"created_at":"2024-11-09T22:19:08.698Z","updated_at":"2025-02-23T23:46:03.878Z","avatar_url":"https://github.com/deve-sh.png","language":"TypeScript","readme":"# `useFetch` - A Simple hook-based fetcher and caching implementation\n\nRead the blog post about building this library: https://blog.devesh.tech/post/creating-our-own-swr\n\n### Features\n\n- Reactivity Baked In\n- Caching of data cross-app\n- Realtime updates cross-app\n- Options to revalidate data on mount and on focus of browser\n- Fallback Data support for server-side rendering\n- Conditional Fetching\n- Global Config Provider\n- Global Config Retreival Hook\n\n### Good to haves but not a part of the bundle yet\n\n- Error Retries\n\n### Usage\n\n#### Simple Usage\n\n```typescript\nuseFetch(\n    key: string | null,\n    options?: {\n        revalidateOnMount?: boolean,\n        revalidateOnFocus?: boolean,\n        dedupingInterval?: milliseconds,\n        fallbackData?: any,\n        fetcher?: (key: string) =\u003e Promise\u003cany\u003e;\n\t    dedupingInterval?: number;\n\t    onSuccess?: (data: any, key: string | null, config: options) =\u003e any;\n\t    onError?: (error: Error, key: string | null, config: options) =\u003e any;\n    }\n)\n```\n\n```javascript\nimport useFetch from \"use-fetch\";\n\nconst Component = () =\u003e {\n\tconst { data, error, isValidating, revalidate } = useFetch(\"/api/v1/data\");\n\n\tif (isValidating) return \"Loading\";\n\tif (error) return `Error: ${error.message}`;\n\treturn (\n\t\t\u003c\u003e\n\t\t\tData: {data}\n\t\t\t\u003cButton onClick={() =\u003e revalidate()}\u003eRefetch\u003c/Button\u003e\n\t\t\u003c/\u003e\n\t);\n};\n```\n\n#### Revalidation\n\nUse\n\n```javascript\nrevalidate(newDate?: any, refetchFromAPI?: boolean)\n```\n\nEvery revalidation fetches data from the API in the background, you can disable that by passing false as the second argument.\n\n```javascript\nconst { data, revalidate } = useFetch(\"/api/v1/data\");\n\nrevalidate(); // Just make the API call again and populate the cache\nrevalidate(localData); // Set the data and cache to localData, but make API Call in the background to update with real data. Like Optimistic Rendering\nrevalidate(localData, false); // Set the data and cache to localData and do not make an API Call in the background\n```\n\n#### Config Provider\n\nFor multiple useFetch hooks, it's cumbersome to pass config/options to each of them separately. Hence, `use-fetch` comes with a `FetchProvider` context provider to share the config among all hooks.\n\n```typescript\nimport { FetchProvider } from \"use-fetch\";\n\nreturn (\n\t\u003cFetchProvider\n\t\tvalue={{\n\t\t\trevalidateOnMount: boolean,\n\t\t\trevalidateOnFocus: boolean,\n\t\t\tdedupingInterval: number(milliseconds),\n\t\t\tfallback: Record\u003cstring, any\u003e,\n\t\t\tfetcher: (key) =\u003e any,\n\t\t\tdedupingInterval: number,\n\t\t}}\n\t\u003e\n\t\t... All components containing useFetch hooks\n\t\u003c/FetchProvider\u003e\n);\n```\n\n#### Global Config Hook\n\nRetrieve the global config for your fetcher hooks using the `useFetchConfig` hook.\n\n```typescript\nimport { useFetchConfig } from \"use-fetch\";\n\nconst {\n\trevalidate,\n\tfetcher,\n\tfallback,\n\tcache,\n\tdedupingInterval,\n\trevalidateOnMount,\n\trevalidateOnFocus,\n} = useFetchConfig();\n\n// This revalidate works differently.\n// It takes 3 args instead of 2.\nrevalidate(\n    keyOfFetcherYouWantToUpdate,\n    localData?,\n    refetchFromAPI?\n);\n```\n\n#### Fallback Data for SSR/SSG\n\n```javascript\nconst key = \"/api/v1/data\";\n\nconst Page = ({ fallbackData }) =\u003e {\n\tconst { data } = useFetch(key, { fallbackData: fallbackData[key] });\n\n\t// or\n\treturn (\n\t\t\u003cFetchProvider value={{ fallback: fallbackData }}\u003e\n\t\t\t{/* \n            All hooks internally would either use their on fallback data or the fallback data from the above provider corresponding to their keys. \n        */}\n\t\t\t...\n\t\t\u003c/FetchProvider\u003e\n\t);\n};\n\nexport const getStaticProps = async () =\u003e {\n\tconst data = await fetchData(key);\n\treturn { props: { fallbackData: { [key]: data } } };\n};\n\nexport default Page;\n```\n\n#### Handling errors and success\n\nUse the `onSuccess` and `onError` handlers for handling the completion and error-ing of the API Calls.\n\n```javascript\nuseFetch(\"/api/v1/data\", {\n\tonSuccess: (data, key, config) =\u003e {\n\t\tconsole.log(\"Data fetched:\", data);\n\t},\n\tonError: (error, key, config) =\u003e {\n\t\tconsole.log(\"Error while fetching:\", error);\n\t},\n});\n```\n\nOr you could use reactivity to your advantage.\n\n```javascript\nuseEffect(() =\u003e {\n\tif (data !== undefined) console.log(\"Data fetched:\", data);\n}, [data]);\n\nuseEffect(() =\u003e {\n\tif (error !== undefined) console.log(\"Error while fetching:\", error);\n}, [error]);\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeve-sh%2Fusefetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeve-sh%2Fusefetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeve-sh%2Fusefetch/lists"}