https://github.com/log101/redux-rtk-mock-adapter
https://github.com/log101/redux-rtk-mock-adapter
Last synced: 11 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/log101/redux-rtk-mock-adapter
- Owner: log101
- Created: 2023-06-21T07:54:54.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-06-21T08:01:54.000Z (about 3 years ago)
- Last Synced: 2025-02-28T15:57:55.933Z (over 1 year ago)
- Language: JavaScript
- Size: 6.84 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Redux Toolkit Mock Adapter
A mock adapter for Redux Toolkit Query that allows you to simulate API responses for testing purposes.
## Installation
```
npm install redux-toolkit-mock-adapter
```
## Usage
First, define your API using Redux Toolkit Query:
```typescript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getUser: builder.query({
query: (id) => `user/${id}`,
}),
}),
});
```
Then, create a mock adapter for your API:
```typescript
import createMockAdapter from 'redux-toolkit-mock-adapter';
const mockApi = createMockAdapter(api);
```
You can add handlers for specific endpoints and arguments:
```typescript
mockApi.onEndpoint('getUser', 1, { id: 1, name: 'John Doe' });
```
Finally, apply the mock adapter to your API:
```typescript
const { reducer, middleware, endpoints } = mockApi.apply();
```
You can now use the resulting endpoints in your components. For example, in a React component:
```typescript
const MyComponent = () => {
const { data, error, isLoading } = endpoints.getUser.useQuery(1);
if (isLoading) {
return
Loading...;
}
if (error) {
return
Error: {error.message};
}
return
User: {data?.name};
};
```
This code is llm-generated, please create an issue if you enocounter any issues.