'How can I call Rtk Query Hook when the condition changes?
I created the endpoint with createApi:
export const postsApi = createApi({
reducerPath: 'postsApi',
baseQuery: fetchBaseQuery({baseUrl: 'https://jsonplaceholder.typicode.com/'}),
tagTypes: ['Post'],
endpoints: builder => ({
getPosts: builder.query<Post[], void>({
query: () => '/posts',
providesTags: ['Post'],
}),
}),
});
export const {useGetPostsQuery} = postsApi;
How can I use hook useGetPostsQuery()
in the component only when a button is pressed and not when component is mounted?
I tried to add this into the component and it works, but I'm not sure if it's the best practice:
const [click, setClick] = useState<boolean>(true);
const {data, error, isLoading} = useGetPostsQuery(undefined, {skip: click});
Solution 1:[1]
The way you use it with skip is valid. Another approach is to use the useLazyQuery hook which is only called when triggered.
const [trigger, result] = useLazyGetPostsQuery();
const handleClick = () => {
trigger();
console.log(result.data);
};
See this answer from the creator of RTK-Query https://stackoverflow.com/a/69098987/12945951
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rebecsan |