Here is a working example of how to get rtk-query to run in nodejs
Here is a list of things that are crucial to get this working in nodejs
- polyfill
window.fetch
for nodejs
- custom settings prop
{ fetchFn }
to the fetchBaseQuery
- using rtk-query without hooks means spreading the store around and dispatching to it the predifined actions of rtk-query such as
api.endpoints.getCharacters.initiate()
index.js
import { getCharacters } from "./store/characterService.js";
import fetch, { Headers, Request } from "node-fetch";
globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;
const init = async () => {
const data = await getCharacters();
console.log(data);
};
init();
store.js
import redux from "@reduxjs/toolkit";
import reduxQuery from "@reduxjs/toolkit/dist/query/index.js";
import fetch from "node-fetch";
export const api = reduxQuery.createApi({
reducerPath: "api",
baseQuery: reduxQuery.fetchBaseQuery({
baseUrl: "https://rickandmortyapi.com/api",
fetchFn: (...args) => {
return fetch(...args);
},
}),
endpoints: (builder) => ({
getCharacters: builder.query({
query: () => "/character",
}),
getCharacter: builder.query({
query: (id) => `/character/${id}`,
}),
}),
});
let store = null;
const initiateStore = () => {
store = redux.configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
});
};
export const getStore = () => {
if (!store) {
console.log(store);
initiateStore();
}
return store;
};
characterService.js
import { getStore, api } from "./store.js";
export const getCharacters = async () => {
const store = getStore();
const { data } = await store.dispatch(api.endpoints.getCharacters.initiate());
return data;
};
export const getCharacter = async (id) => {
const store = getStore();
const { data } = await store.dispatch(
api.endpoints.getCharacter.initiate(id)
);
return data;
};
Also fetchFn is a property to configure BaseQuery, queryFn is a property to configure individual endpoints and overwrites the settings for BaseQuery for that endpoint