{"id":19404135,"url":"https://github.com/p32929/use-megamind","last_synced_at":"2026-01-23T09:21:58.263Z","repository":{"id":246769761,"uuid":"822765337","full_name":"p32929/use-megamind","owner":"p32929","description":"A simple react hook for managing asynchronous function calls with ease on the client side","archived":false,"fork":false,"pushed_at":"2024-10-14T08:32:20.000Z","size":24,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-10-14T11:42:07.290Z","etag":null,"topics":["async","asynchronous-tasks","axios","client-side-javascript","data","data-fetching","easy","fetch","generics","hooks","javascript","npm","painless","promise","query","react","rest","simple","small","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/use-megamind","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/p32929.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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":"2024-07-01T19:20:05.000Z","updated_at":"2024-10-14T08:32:24.000Z","dependencies_parsed_at":null,"dependency_job_id":"586425a0-b6ac-4679-b770-0138f79daa2a","html_url":"https://github.com/p32929/use-megamind","commit_stats":null,"previous_names":["p32929/use-megamind"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p32929%2Fuse-megamind","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p32929%2Fuse-megamind/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p32929%2Fuse-megamind/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p32929%2Fuse-megamind/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/p32929","download_url":"https://codeload.github.com/p32929/use-megamind/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223947792,"owners_count":17230094,"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":["async","asynchronous-tasks","axios","client-side-javascript","data","data-fetching","easy","fetch","generics","hooks","javascript","npm","painless","promise","query","react","rest","simple","small","typescript"],"created_at":"2024-11-10T11:33:13.947Z","updated_at":"2026-01-23T09:21:58.201Z","avatar_url":"https://github.com/p32929.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# use-megamind\n\nA simple React hook for managing asynchronous function calls with ease on the client side, now with global validation, append functionality, and more.\n\n## Installation\n\n```bash\nnpm install use-megamind\n```\n\nor\n\n```bash\nyarn add use-megamind\n```\n\n## Motivation\n\nThe goal behind `use-megamind` was to build a custom solution for managing asynchronous operations that’s simple to implement, especially in existing projects. It works not only for data fetching but for any kind of async operation, making it a more lightweight alternative to React Query. While React Query is awesome, I wanted a solution that doesn't require extensive documentation to get started. `use-megamind` is small, efficient, and does the job without extra complexity.\n\n## Global Configuration\n\nYou can now set global validation logic for all `useMegamind` instances via the following functions:\n\n- `setGlobalValidateOnSuccess`: Define a global function to validate the result of a successful async call.\n- `setGlobalValidateOnError`: Define a global function to validate errors during an async call.\n\nThese validations will run across all hooks unless overridden locally in individual hooks.\n\n```ts\nimport { setGlobalValidateOnSuccess, setGlobalValidateOnError } from \"use-megamind\";\n\n// Example: Set global validation for success\nsetGlobalValidateOnSuccess((data) =\u003e {\n  // Return true to proceed with onSuccess, false otherwise\n  return data !== null;\n});\n\n// Example: Set global validation for error\nsetGlobalValidateOnError((error) =\u003e {\n  // Return true to proceed with onError, false otherwise\n  return error !== 'IGNORE';\n});\n```\n\n## How to Use\n\n### Example 1: Async function without parameters\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction1() {\n  return new Promise((res, rej) =\u003e {\n    setTimeout(() =\u003e {\n      res(\"Hello world\");\n    }, 1000);\n  });\n}\n\nexport default function Home() {\n  const { data, error, isLoading } = useMegamind(testAsyncFunction1);\n\n  return \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e;\n}\n```\n\n### Example 2: Async function with parameters\n\n\u003e `functionParams`: The async function parameters, passed one by one (Default: `null`)\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction2(ms: number) {\n  return new Promise((res) =\u003e {\n    setTimeout(() =\u003e res(`Waited ${ms} ms`), ms);\n  });\n}\n\nexport default function Home() {\n  const { data, error, isLoading } = useMegamind(testAsyncFunction2, {\n    functionParams: [1000],\n  });\n\n  return \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e;\n}\n```\n\n### Example 3: Async function call on a button click\n\n\u003e `callRightAway`: Whether the async function should be called when the component mounts (Default: `true`)\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction3(ms: number) {\n  return new Promise((res) =\u003e {\n    setTimeout(() =\u003e res(`Hello after ${ms} ms`), ms);\n  });\n}\n\nexport default function Home() {\n  const { data, call } = useMegamind(testAsyncFunction3, {\n    options: {\n      callRightAway: false,\n    },\n  });\n\n  return (\n    \u003c\u003e\n      \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e call(1000)}\u003eCall\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Example 4: Adding options\n\n`useMegamind` provides a variety of options to control behavior:\n\n- `maxCalls`: Maximum number of times the async function can be called (Default: `'infinite'`)\n- `minimumDelayBetweenCalls`: Minimum delay between two consecutive calls (Default: `0ms`)\n- `debug`: Enable debug logging (Default: `false`)\n- `callRightAway`: Whether to call the async function when the component mounts (Default: `true`)\n- `cache`: Cache response until the page is reloaded (Default: `false`)\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction4(ms: number) {\n  return new Promise((res) =\u003e {\n    setTimeout(() =\u003e res(`Hello after ${ms} ms`), ms);\n  });\n}\n\nexport default function Home() {\n  const { data, call } = useMegamind(testAsyncFunction4, {\n    options: {\n      callRightAway: false,\n      debug: true,\n      maxCalls: 1,\n      minimumDelayBetweenCalls: 1000,\n    },\n  });\n\n  return (\n    \u003c\u003e\n      \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e call(1000)}\u003eCall\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Example 5: Append fetched data\n\nYou can now append the fetched data to the existing state using the `callToAppend` function.\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction5(ms: number) {\n  return new Promise((res) =\u003e {\n    setTimeout(() =\u003e res(`Fetched after ${ms} ms`), ms);\n  });\n}\n\nexport default function Home() {\n  const { data, callToAppend } = useMegamind(testAsyncFunction5, {\n    options: {\n      callRightAway: false,\n    },\n  });\n\n  return (\n    \u003c\u003e\n      \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e callToAppend(1000)}\u003eAppend Data\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Example 6: Event callbacks and validations\n\nYou can now define validations for both success and error callbacks, either locally or globally.\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction6(ms: number) {\n  return new Promise((res, rej) =\u003e {\n    if (ms \u003c 500) {\n      rej(\"Error: Too fast!\");\n    } else {\n      setTimeout(() =\u003e res(`Hello after ${ms} ms`), ms);\n    }\n  });\n}\n\nexport default function Home() {\n  const { data, error, isLoading, call } = useMegamind(testAsyncFunction6, {\n    options: {\n      callRightAway: false,\n    },\n    events: {\n      validateOnSuccess(data) {\n        // Proceed with onSuccess only if data is valid\n        return data.includes(\"Hello\");\n      },\n      onSuccess(data) {\n        console.log(\"Success: \", data);\n      },\n      validateOnError(error) {\n        // Proceed with onError only if the error is valid\n        return error.includes(\"Error\");\n      },\n      onError(error) {\n        console.error(\"Error: \", error);\n      },\n    },\n  });\n\n  return (\n    \u003c\u003e\n      \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e\n      \u003cp\u003e{JSON.stringify(error)}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e call(400)}\u003eCall with Error\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e call(600)}\u003eCall with Success\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n### Example 7: Clearing or resetting state\n\n- `clear`: Clears the state but keeps the cache.\n- `reset`: Resets everything, including the cache and call counter.\n\n```ts\n\"use client\";\nimport useMegamind from \"use-megamind\";\n\nfunction testAsyncFunction7(ms: number) {\n  return new Promise((res) =\u003e {\n    setTimeout(() =\u003e res(`Hello after ${ms} ms`), ms);\n  });\n}\n\nexport default function Home() {\n  const { data, call, clear, reset } = useMegamind(testAsyncFunction7, {\n    options: {\n      callRightAway: false,\n    },\n  });\n\n  return (\n    \u003c\u003e\n      \u003cp\u003e{JSON.stringify(data)}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e call(1000)}\u003eCall\u003c/button\u003e\n      \u003cbutton onClick={clear}\u003eClear\u003c/button\u003e\n      \u003cbutton onClick={reset}\u003eReset\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n## Contribution\n\nIf you'd like to contribute by adding features or fixing bugs, please open an issue before submitting a pull request.\n\n## License\n\n```\nMIT License\n\nCopyright (c) 2024 Fayaz Bin Salam\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp32929%2Fuse-megamind","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fp32929%2Fuse-megamind","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp32929%2Fuse-megamind/lists"}