I would like to modify the response received from the backend with the transformResponse function but I get an error even when I only return the first argument ""baseQueryReturnValue"".
export const categoryApiSlice = createApi({
reducerPath: "Categories",
baseQuery: fakeBaseQuery(),
tagTypes: ["CategoriesTag"],
endpoints: (builder) => ({
getAllCategories: builder.query<Category[], void>({
async queryFn() {
try {
const ref = collection(db, "categories");
const querySnapshot = await getDocs(ref);
let categories: Category[] = [];
querySnapshot?.forEach((doc) => {
categories.push({ id: doc.id, ...doc.data() } as Category);
});
return { data: categories };
} catch (error: any) {
console.error(error.message);
return { error: error.message };
}
},
///// here i'm getting the error pasted below //////
transformResponse(baseQueryReturnValue, meta, arg) {
return baseQueryReturnValue
},
providesTags: ["CategoriesTag"],
}),
}),
});
export const { useGetAllCategoriesQuery } = categoryApiSlice;
here is the type script error Type '(baseQueryReturnValue: unknown, meta: {}, arg: void) => unknown' is not assignable to type '(baseQueryReturnValue: unknown, meta: {}, arg: void) => Category[] | Promise<Category[]>'. Type 'unknown' is not assignable to type 'Category[] | Promise<Category[]>'.ts(2322) endpointDefinitions.d.ts(54, 5): The expected type comes from property 'transformResponse' which is declared here on type 'OmitFromUnion<QueryDefinition<void, BaseQueryFn, "CategoriesTag", Category[], "Categories">, "type">'
I also tried not to use transformResponse but rather to modify the response received in the queryFn but without success.
transformResponse
exists because when you use the query
argument to a query definition, you only create the input to your baseQuery
and have no control over what happens afterwards. If only query
, but not transformResponse
, existed, you had no control over the final return value.
Now, when you use queryFn
, you have full control over the final return value already - you write the full queryFn
function after all, and you can do any kind of transformation inside of it already.
That's why transformResponse
only works with query
, but doesn't exist as an option when you use queryFn
.
It's not necessary in that context and would only split up your logic instead of keeping it in one place.
=> You cannot use transformResponse
and queryFn
at the same time. It doesn't make sense, so it's not possible.
Do your transformation inside of queryFn
instead.