preparing Headers with redux toolkit and createApi - reactjs

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!

Related

How to use RTK-Query with Supabase

I have a project already configured with Supabase and using Redux-Toolkit. I have never used RTK-Query and I am just learning but after reading in the docs and looking for similar questions I have created a supabaseApi.js file which looks like:
import { createApi, fakeBaseQuery } from '#reduxjs/toolkit/query';
export const supabaseApi = createApi({ baseQuery: fakeBaseQuery(),
endpoints: (builder) =({
getStudents: builder.query({
queryFn: async () ={
const students = await supabase
.from('students')
.select()
return {students, error}
}
})
}) })
export const { useGetStudentsQuery } = supabaseApi;
However, when I call the useGetStudentsQuery() to get the students table I receive an error in the console telling me that "useGetStudentsQuery is not a function". I also noticed that when I begin to write the useGet function, it seems it hasn't been automatically created as I don't get the Visual Studio hints.
What is it that I am doing wrong? Thanks.
A few things:
to have the hooks, you have to import from '#reduxjs/toolkit/query/react';
the queryFn has to return either { data } or { error }, not { student }
your code does not seem to have a error variable, but tries to return it.
so:
import { createApi, fakeBaseQuery } from '#reduxjs/toolkit/query/react';
export const supabaseApi = createApi({ baseQuery: fakeBaseQuery(),
endpoints: (builder) =({
getStudents: builder.query({
queryFn: async () ={
const students = await supabase
.from('students')
.select()
return { data: students }
}
})
}) })
export const { useGetStudentsQuery } = supabaseApi;

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