{"_id":"@domeadev/with-fetch","name":"@domeadev/with-fetch","dist-tags":{"latest":"0.0.1"},"versions":{"0.0.1":{"name":"@domeadev/with-fetch","version":"0.0.1","description":"A lightweight utility for managing asynchronous data fetching operations while updating state in modern JavaScript applications.","types":".dist/index.d.ts","main":".dist/index.js","module":".dist/index.mjs","exports":{".":{"import":"./.dist/index.mjs","require":"./.dist/index.js"}},"keywords":["typescript","fetch","async","state management","data fetching"],"author":{"name":"domeafavour"},"license":"MIT","devDependencies":{"tsup":"^8.0.2","typescript":"^5.4.5","vitest":"^2.1.8"},"repository":{"type":"git","url":"git+https://github.com/domeafavour/with-fetch.git"},"publishConfig":{"access":"public"},"scripts":{"test":"vitest","build":"tsup"},"_id":"@domeadev/with-fetch@0.0.1","bugs":{"url":"https://github.com/domeafavour/with-fetch/issues"},"homepage":"https://github.com/domeafavour/with-fetch#readme","_integrity":"sha512-u/QbYDjKRFqusAIxdP5xYeJdXGCu/QMW6PUqq/o8OKAhoIyYqesKdoDYI3uzQaKrAEZv4c4s5nWhCZUAX+kL/g==","_resolved":"/tmp/01755fcf14caef62da892f29b8f0e634/domeadev-with-fetch-0.0.1.tgz","_from":"file:domeadev-with-fetch-0.0.1.tgz","_nodeVersion":"18.20.8","_npmVersion":"10.8.2","dist":{"integrity":"sha512-u/QbYDjKRFqusAIxdP5xYeJdXGCu/QMW6PUqq/o8OKAhoIyYqesKdoDYI3uzQaKrAEZv4c4s5nWhCZUAX+kL/g==","shasum":"b6278804f96fe5d0be37f8bb8d0e8e68e82b3b2a","tarball":"https://registry.npmjs.org/@domeadev/with-fetch/-/with-fetch-0.0.1.tgz","fileCount":8,"unpackedSize":16375,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDbOkOC+fW7eckT1hz5PfchAwYC2oRaqENhxouZ7vVSHwIhAIxnc0jeR/zX7jv+CQ7oyUsRleMZjfiA/WRfiteh6wS+"}]},"_npmUser":{"name":"domeafavour","email":"1455123087@qq.com"},"directories":{},"maintainers":[{"name":"domeafavour","email":"1455123087@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/with-fetch_0.0.1_1749107173678_0.21553678433875745"},"_hasShrinkwrap":false}},"time":{"created":"2025-06-05T07:06:13.605Z","0.0.1":"2025-06-05T07:06:13.864Z","modified":"2025-06-05T07:06:14.123Z"},"maintainers":[{"name":"domeafavour","email":"1455123087@qq.com"}],"description":"A lightweight utility for managing asynchronous data fetching operations while updating state in modern JavaScript applications.","homepage":"https://github.com/domeafavour/with-fetch#readme","keywords":["typescript","fetch","async","state management","data fetching"],"repository":{"type":"git","url":"git+https://github.com/domeafavour/with-fetch.git"},"author":{"name":"domeafavour"},"bugs":{"url":"https://github.com/domeafavour/with-fetch/issues"},"license":"MIT","readme":"# With Fetch\n\nA lightweight utility for managing asynchronous data fetching operations while updating state in modern JavaScript applications.\n\n[![npm version](https://img.shields.io/npm/v/@domeadev/with-fetch.svg)](https://www.npmjs.com/package/@domeadev/with-fetch)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Overview\n\nWith Fetch is a simple yet powerful utility for handling data fetching operations that need to update state. It works well with state management libraries and provides a clean way to transform responses and update state in a single operation.\n\n## Installation\n\n### npm\n\n```bash\nnpm install @domeadev/with-fetch\n```\n\n### yarn\n\n```bash\nyarn add @domeadev/with-fetch\n```\n\n### Using pnpm\n\n```bash\npnpm add @domeadev/with-fetch\n```\n\n## Usage\n\n### Basic Example\n\n```ts\nimport { useMemo, useEffect } from \"react\";\nimport { createWithFetchFn } from \"@domeadev/with-fetch\";\n\n// Example with React's useState\nfunction MyComponent() {\n  const [state, setState] = useState({\n    data: null,\n    loading: false,\n    error: null,\n  });\n\n  const withFetch = useMemo(\n    () =>\n      createWithFetchFn((updater) => {\n        setState((prev) => ({ ...prev, ...updater(prev) }));\n      }),\n    []\n  );\n\n  useEffect(() => {\n    // Automatically updates state.data with the result\n    withFetch(\n      () => fetch(\"https://api.example.com/data\").then((res) => res.json()),\n      \"data\"\n    );\n  }, []);\n\n  return null;\n}\n```\n\n### Advanced Usage\n\n#### With Transform and Reducer\n\n```typescript\nconst withFetch = createWithFetchFn(setState);\n\n// Transform the response and update multiple state fields\nawait withFetch(() => fetch(\"/api/users\").then((res) => res.json()), {\n  // Transform the response\n  transform: (users) =>\n    users.map((user) => ({\n      ...user,\n      fullName: `${user.firstName} ${user.lastName}`,\n    })),\n\n  // Update state with transformed result\n  reducer: (transformedUsers, currentState) => ({\n    users: transformedUsers,\n    lastFetched: new Date(),\n  }),\n});\n```\n\n#### With Just a Reducer\n\n```typescript\nawait withFetch(\n  () => fetch(\"/api/stats\").then((res) => res.json()),\n  (result, currentState) => ({\n    stats: result,\n    hasStats: result.length > 0,\n    lastUpdated: new Date(),\n  })\n);\n```\n\n#### Synchronous State Management with Zustand and React Query\n\n```tsx\nimport { createWithFetchFn } from \"@domeadev/with-fetch\";\nimport { create } from \"zustand\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nconst useStore = create((set) => ({\n  users: [] as { id: number; firstName: string; lastName: string }[],\n  withFetch: createWithFetchFn(set),\n}));\n\nfunction fetchUsers(): Promise<\n  { id: number; first_name: \"john\"; last_name: \"doe\" }[]\n> {\n  return fetch(\"/api/users\").then((res) => res.json());\n}\n\nfunction useUsersQuery() {\n  const withFetch = useStore((state) => state.withFetch);\n  return useQuery({\n    queryKey: [\"users\"],\n    queryFn: () =>\n      withFetch(fetchUsers, {\n        transform: (users) =>\n          users.map((user) => ({\n            id: user.id,\n            firstName: user.first_name,\n            lastName: user.last_name,\n          })),\n        reducer: (transformedUsers, currentState) => ({\n          users: transformedUsers,\n        }),\n      }),\n  });\n}\n\nfunction UsersList() {\n  const users = useStore((state) => state.users);\n  return (\n    <ul>\n      {users.map((user) => (\n        <li key={user.id}>\n          {user.firstName} {user.lastName}\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nfunction App() {\n  const { isLoading, error } = useUsersQuery();\n\n  if (isLoading) return <div>Loading...</div>;\n  if (error) return <div>Error fetching users</div>;\n\n  return (\n    <div>\n      <h1>Users</h1>\n      <UsersList />\n    </div>\n  );\n}\n```\n\n## API Reference\n\n### `createWithFetchFn(update)`\n\nCreates a `withFetch` function that can be used to fetch data and update state.\n\n- **Parameters:**\n\n  - `update`: Function that accepts an updater function `(state) => partialState`\n\n- **Returns:** A `withFetch` function with multiple overloaded signatures:\n\n### `withFetch` Signatures\n\n#### Direct key update\n\n```typescript\nwithFetch<K extends keyof S>(\n  fetcher: () => Promise<S[K]>,\n  key: K\n): Promise<S[K]>\n```\n\n#### With transform and reducer\n\n```typescript\nwithFetch<T, R = T>(\n  fetcher: () => Promise<T>,\n  options: {\n    transform?: (response: T) => R;\n    reducer: (result: R, state: S) => Partial<S>;\n  }\n): Promise<R>\n```\n\n#### With just a reducer\n\n```typescript\nwithFetch<T>(\n  fetcher: () => Promise<T>,\n  reducer: (result: T, state: S) => Partial<S>\n): Promise<T>\n```\n\n## License\n\nMIT © [domeafavour](https://github.com/domeafavour)\n","readmeFilename":"README.md","_rev":"1-edb5233432d5848dcf7d1ad1392117bf"}