4

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});
Red Developer
  • 41
  • 1
  • 1
  • 5

2 Answers2

9

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

rebecsan
  • 116
  • 2
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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vineet Gautam
  • 21
  • 2
  • 3