How to set initialState in RTK query? - reactjs

I am new to RTK and RTK query.
I am trying to set up initial configuration using the official documentation.
export const pokemonApi = createApi({
reducerPath: 'pokemonApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
endpoints: (builder) => ({
getPokemonByName: builder.query<Pokemon, string>({
query: (name) => `pokemon/${name}`,
}),
}),
})
The official docs didn't suggest how can i set initial state here
I tried passing initialState as the first argument
export const pokemonApi = createApi({
initialState,
reducerPath: "pokemonApi",
baseQuery: fetchBaseQuery({ baseUrl: "https://pokeapi.co/api/v2/" }),
endpoints: (builder) => ({
getPokemonByName: builder.query<Pokemon, string>({
query: (name) => `pokemon/${name}`,
}),
}),
});
This code leads to the following error:
Object literal may only specify known properties, and 'initialState' does not exist in type 'CreateApiOptions<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, { getPokemonByName: QueryDefinition<...>; }, "pokemonApi", never>'
How exactly can I set the initial state RTK query?

You don't. The purpose of RTK Query is to fetch data from a server. It doesn't have an "initial state".

Related

preparing Headers with redux toolkit and createApi

Does anyone know how to prepare headers to match a key given by an API? I'm trying to connect to Urban Dictionary API using a key and host name but I'm unsure how to implement that using redux toolkit.
Here's what I have, I know it's very wrong:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
import { TWord } from "../../types/wordType";
export const apiSlice = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: "https://mashape-community-urban-dictionary.p.rapidapi.com/define",
prepareHeaders: (headers) => {
headers.set(
"X-RapidAPI-Key",
"<my key>"
),
headers.set(
"X-RapidAPI-Host",
"mashape-community-urban-dictionary.p.rapidapi.com"
);
},
}),
tagTypes: ["Words"],
endpoints: (builder) => ({
getWord: builder.query({
query: (word: string) => ({
url: `/${word}`,
}),
}),
}),
});
export const { useGetWordQuery } = apiSlice;
Any ideas?
Okay, found the solution:
The query for getting a word needs to be /define?term=${word}, if anyone might need it in the future!

Can't assign to object array when fetching data with RTK Query

I have come across a problem that I do not understand while trying to integrate redux toolkit and more specifically RTK Query into my project. All I want to do is fetch an object array from my backend using a query hook, pass this data into my component and alter some of the elements inside the data based on user actions.
I am copying the incoming array so as not to mutate the original.
I can replace entire objects in the array with 'blah' but if I try to alter a single value within one of the objects I get:
TypeError: Cannot assign to read only property 'title' of object '#<Object>'
This problem didn't arise when I was using fetch().
I have been stuck on this for days!!!
apiSlice
import { createApi, fetchBaseQuery } from '#reduxjs/toolkit/query/react';
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: process.env.devUrl }),
tagTypes: ['categories'],
endpoints: (builder) => ({
getCategories: builder.query({
query: () => 'categories/includingJobs',
transformResponse: (response) => response.data.data,
providesTags: ['categories'],
}),
}),
});
export const { useGetCategoriesQuery} = apiSlice;
Component
import {
useGetCategoriesQuery,
} from '../features/api/apiSlice';
const Test = () => {
const {
data: categories,
isLoading,
isSuccess,
isError,
error,
} = useGetCategoriesQuery();
if (isSuccess) {
let categoriesCopy = JSON.parse(JSON.stringify(categories));
//This is the line that breaks everything. Why?
categoriesCopy[0].title = 'new title';
}
return <h1>Something rendered</h1>;
};
export default Test;

how to wrap api in enhanceEndpoints/injectEndpoints with RTK with correct TS?

I have a packet from npm that creates for me basic api with createApi() and in the same file it wraps this api with my custom function with that I can extend it with enhanceEndpoints, it's two different files and ts can't view types that I provided in my custom function, is it possible to make it in 2 files and to force to work ts with it?
for better undestanding I have main file like this:
export const api = createApi({
reducerPath: 'api/test',
baseQuery : fetchBaseQuery({
baseUrl: '/',
//some options
}),
endpoints: (build) => ({
//some initial endpoints
})
});
customFunctionProvided(api);
export default api;
second file:
export const customFunctionProvided = (api: typeof apiType) => {
api.enhanceEndpoints({
//some logic
}).injectEndpoints({ endpoints: (builder) => ({
getSomething: builder.query({
query: () => ({
url: 'url',
})
}),
}) });
};
so, I import first file in my project and ts can't find for example useGetSomethingQuery()...(
is it has a way to work around?

How to get not 20 elements from the server, but for example 5? (redux toolkit rtk query)

export const rickandmortyApi = createApi({
reducerPath: 'rickandmorty/api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://rickandmortyapi.com/api/' }),
endpoints: (builder) => ({
searchCharacter: builder.query<ServerResponse, any>({
query: (page = 1) => `character?page=${page}`
}),
}),
})
export const {useSearchCharacterQuery} = rickandmortyApi
[1][Server responce]
[1]: https://i.stack.imgur.com/qR0hr.png
As per the documentation at https://rickandmortyapi.com/documentation/#rest:
character?page=${page}&count=5

I have a problem with firebase after post a data

I'm working with RTK query in my react project as a fetching/caching module which is great but after POST a data to my firebase database something like a random id which made up by firebase subcategorizes all my data and disrupts the structure of my data
I put a picture which shows how data getting store on the firebase :
and below code is the RTK query handler
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
import {
AllBurgerType,
BurgerType,
} from "../*********************";
export const burgerApi = createApi({
reducerPath: "burgerApi",
tagTypes: ["Ingredients"],
baseQuery: fetchBaseQuery({
baseUrl:
"https://************************.firebasedatabase.app",
}),
endpoints: (builder) => ({
// I've rid other methods
addIngredients: builder.mutation({
query: (initialIngredients) => ({
url: "/.json",
method: "POST",
body: initialIngredients,
}),
invalidatesTags: ["Ingredients"],
}),
}),
});
export const {
useGetIngredientsQuery,
useAddIngredientsMutation,
useEditIngredientsMutation,
} = burgerApi;
and add new data like on the other file like this :
import { useAddIngredientsMutation } from "../../../../Api/apiSlice";
const [addNewIng, { isLoading, isSuccess }] =
useAddIngredientsMutation();
await addNewIng(store.getState().burger).unwrap();
how should I prevent this

Resources