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

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

Related

How to set initialState in RTK query?

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".

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!

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?

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

Access to localStorage from createApi RTK on first page load

I have a case where I need to read my .env file on page load and if there is a specific value then I dispatch that value in my store, where I have createApi => baseUrl needs to access to that value, or localStorage, in order to use it as making an api call, here is an example of my code:
App.tsx
React.useEffect(() => {
const myCustomEndpoint = window._env_.MYENDPOINT;
if(myCustomEndpoint) {
dispatch(setApiEndpoint(myCustomEndpoint));
}
}, [])
src/redux/reducerSlice.ts
export const reducerSlice = createSlice({
//...more slices
setApiEndpoint: (state, action: PayloadAction<string>) => {
state.apiEndpoint = action.payload;
localStorage.removeItem('api');
localStorage.setItem('api', state.apiEndpoint);
}
})
src/services/api.ts
const baseUrl = localStorage.getItem(config.apiEndpoint) || '';
export const dataApis = createApi({
reducerPath: 'dataApis',
baseQuery: fetchBaseQuery({ baseUrl }), // here I cannot get the API for first time the page load
endpoints: (builder) => ({
// my endpoints
})
So is there a way how to access the localStorage of the api endpoint which I have set for the first time my app was loaded?
I think you can set the endpoint directly in the createApi method, so just use like this for example: fetchBaseQuery({ baseUrl: window._env_.MYENDPOINT || '' }).

Resources