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.
2
Answers
The return value of
transformResponse
has to be anResultType | Promise<ResultType>
but baseQueryReturnValue is of typeBaseQueryResult<BaseQuery>
(https://redux-toolkit.js.org/rtk-query/api/createApi#query-endpoint-definition)
transformResponse
exists because when you use thequery
argument to a query definition, you only create the input to yourbaseQuery
and have no control over what happens afterwards. If onlyquery
, but nottransformResponse
, 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 fullqueryFn
function after all, and you can do any kind of transformation inside of it already.That’s why
transformResponse
only works withquery
, but doesn’t exist as an option when you usequeryFn
.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
andqueryFn
at the same time. It doesn’t make sense, so it’s not possible.Do your transformation inside of
queryFn
instead.