How can I call Rtk Query Hook when the condition changes?
Asked Answered
P

2

5

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});
Pernick answered 3/4, 2022 at 9:4 Comment(0)
B
10

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://mcmap.net/q/514751/-approaches-for-using-rtk-query-hooks-inside-functions

Bobbery answered 25/4, 2022 at 7:28 Comment(0)
S
2

Yes, your implementation is correct. When you pass the second parameter as an object with skip property to the query, it prevents its auto fetching behavior on the mount of the component.

Even the official docs state the same approach https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching

Stick answered 9/6, 2022 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.