How do you pass query parameters to the api using Redux Toolkit RTK Query?
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const baseUrl = 'xxxxxxx';
export const postsApi = createApi({
reducerPath: 'posts',
baseQuery: fetchBaseQuery({ baseUrl }),
endpoints: (builder) => ({
getPostsByYear: builder.query({
query: (start, end) => { // Why is 'end' always undefined???
return {
url: 'posts/',
params: { start, end },
};
},
}),
getPosts: builder.query({
query: () => 'posts/',
}),
getPostByID: builder.query({
query: (name) => `posts/${name}`,
}),
}),
});
export const { useGetPostsQuery, useGetPostsByYearQuery, useGetPostByIDQuery } = postsApi;
When trying to pass parameters from the component only the start
value seems to be recognised. year
is updated by a select element within the <PostOptions/>
component. It's using the useState
hook. The value updates correctly and useGetPostsByYearQuery
is called but the end
parameter is always undefined. So, it seems I'm not defining the api endpoint correctly. Any advise? All I want it to do is send a request in the form http://xxx/posts?start=start&end=end
.
I've even tried hard-coding a string value for the end
parameter, e.g. useGetPostsByYearQuery(year, '2019')
, but it still appears as undefined
withing the api callback so I'm missing something more fundamental.
const Post = () => {
const year = useSelector((state) => state.postOptions.year);
const yearPlusOne = parseInt(year, 10) + 1;
const { data, error, isLoading } = useGetPostsByYearQuery(year, yearPlusOne);
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
<PostHeading />
<PostOptions></PostOptions>
</View>
</SafeAreaView>
);
};
export default Post;
query
only ever takes one argument, that is why yourend
was giving you problems. The answer below shows very well how to get around that :) – Stollings