sample of rtk query
rtk query
Gotcha — you want the conveniences of RTK Query (auto-caching, hooks, centralised state) but without actually hitting a server. That’s totally doable by creating a mock API using fakeBaseQuery
so all data stays local.
Here’s a minimal example:
1️⃣ Install dependencies
npm install @reduxjs/toolkit react-redux
2️⃣ Define your “API” with fakeBaseQuery
src/services/localApi.js
import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react';
let localData = { value: 'Hello World' }; // stored in memory
export const localApi = createApi({
reducerPath: 'localApi',
baseQuery: fakeBaseQuery(),
endpoints: (builder) => ({
getValue: builder.query({
queryFn: () => ({ data: localData }),
}),
setValue: builder.mutation({
queryFn: (newValue) => {
localData = { value: newValue };
return { data: localData };
},
}),
}),
});
export const { useGetValueQuery, useSetValueMutation } = localApi;
3️⃣ Add it to the store
src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import { localApi } from '../services/localApi';
export const store = configureStore({
reducer: {
[localApi.reducerPath]: localApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(localApi.middleware),
});
4️⃣ Use it in a component
src/App.js
import React, { useState } from 'react';
import { useGetValueQuery, useSetValueMutation } from './services/localApi';
function App() {
const { data } = useGetValueQuery();
const [setValue] = useSetValueMutation();
const [input, setInput] = useState('');
return (
<div style={{ padding: 20 }}>
<h2>Value: {data?.value}</h2>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={() => setValue(input)}>Change Value</button>
</div>
);
}
export default App;
✅ How it works
fakeBaseQuery()
stops RTK Query from making HTTP requests.You can store and mutate data in-memory (
localData
in this example).Still get all the nice RTK Query hooks and cache invalidation patterns.
نظرات (۰)
هیچ نظری هنوز ثبت نشده است