{"library":"redux-query-react","title":"Redux Query React Integration","description":"redux-query-react provides the React-specific interface for integrating with redux-query, a library designed for managing network state within Redux applications. It streamlines the process of fetching data, handling optimistic updates, and managing cancellations directly from React components. The current stable release candidate is `3.6.1-rc.2`, indicating active development with ongoing release candidates. While a precise release cadence isn't specified, the project exhibits a feature-driven release model. Key differentiators include its adherence to core Redux principles (middleware, actions, selectors, reducers), ensuring minimal 'magic' and high extensibility, allowing for custom middleware, UI integrations, and network interfaces. It offers both modern React hooks (like `useRequest`, `useMutation`) and higher-order components (`connectRequest`) to colocate data dependencies with components and trigger requests on mount or update, working seamlessly with both functional and class components.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install redux-query-react"],"cli":null},"imports":["import { useRequest } from 'redux-query-react';","import { useMutation } from 'redux-query-react';","import { connectRequest } from 'redux-query-react';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import React from 'react';\nimport { createStore, combineReducers, applyMiddleware } from 'redux';\nimport { Provider } from 'react-redux';\nimport { queriesReducer, queriesMiddleware, QueryConfig } from 'redux-query';\nimport { useRequest, useMutation } from 'redux-query-react';\nimport { createNetworkHandler } from 'redux-query-interface-superagent'; // For a real app, install this\n\n// A mock network handler for demonstration purposes\nconst mockNetworkHandler = createNetworkHandler({\n  adapter: (config) => {\n    console.log('Mock API call:', config.url, config.method, config.body);\n    return new Promise((resolve, reject) => {\n      setTimeout(() => {\n        if (config.url === '/api/users/1') {\n          resolve({\n            status: 200,\n            body: { id: 1, name: 'Alice', email: 'alice@example.com' },\n            headers: new Headers(),\n          });\n        } else if (config.url === '/api/users/1' && config.method === 'PUT') {\n          resolve({\n            status: 200,\n            body: { id: 1, name: config.body.name, email: 'alice@example.com' },\n            headers: new Headers(),\n          });\n        } else {\n          reject({ status: 404, body: 'Not Found', headers: new Headers() });\n        }\n      }, 500);\n    });\n  }\n});\n\n// Setup Redux store with redux-query\nconst rootReducer = combineReducers({\n  queries: queriesReducer,\n  // Add other reducers here\n});\n\nconst store = createStore(\n  rootReducer,\n  applyMiddleware(queriesMiddleware(mockNetworkHandler))\n);\n\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n}\n\n// Define a query config for fetching a user\nconst getUserQuery: QueryConfig = {\n  url: '/api/users/1',\n  update: {\n    entities: (prevEntities: any = {}, newEntities: any) => ({\n      ...prevEntities,\n      user: newEntities.user, // Assuming API returns { user: { ... } }\n    }),\n  },\n  // Map the query response data to a specific key, if needed.\n  // data: (queryState) => queryState.entities.user\n};\n\nconst UserProfile: React.FC = () => {\n  // Use useRequest to fetch user data\n  const { isPending, isFinished, data } = useRequest<User>(getUserQuery);\n\n  // Use useMutation to update user data with optimistic updates\n  const [updateUserName, { isPending: isUpdatingName }] = useMutation(\n    (newName: string) => ({\n      url: '/api/users/1',\n      method: 'PUT',\n      body: { name: newName },\n      update: {\n        entities: (prevEntities: any = {}, newEntities: any) => ({\n          ...prevEntities,\n          user: newEntities.user,\n        }),\n      },\n      optimistic: {\n        entities: (prevEntities: any = {}) => ({\n          ...prevEntities,\n          user: { ...prevEntities.user, name: newName + ' (optimistic)' },\n        }),\n      },\n    })\n  );\n\n  const handleRenameUser = () => {\n    updateUserName('Bob');\n  };\n\n  if (isPending) return <div>Loading user profile...</div>;\n  if (!data) return <div>No user data available.</div>;\n\n  return (\n    <div>\n      <h2>User Profile</h2>\n      <p>ID: {data.id}</p>\n      <p>Name: {data.name} {isUpdatingName && '(Updating...)'}</p>\n      <p>Email: {data.email}</p>\n      <button onClick={handleRenameUser} disabled={isUpdatingName}>Rename to Bob</button>\n    </div>\n  );\n};\n\nconst App: React.FC = () => (\n  <Provider store={store}>\n    <UserProfile />\n  </Provider>\n);\n\nexport default App;\n","lang":"typescript","description":"This example demonstrates how to set up a Redux store with `redux-query`, define a `networkHandler` (mocked here), and use `redux-query-react`'s `useRequest` hook to fetch and display user data, along with `useMutation` for optimistic updates on a user's name.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}