Search code examples
reactjsreduxrtk-query

How to disable RTK Query auto-request fetching?


When I apply an auto-generated hook from createApi. That hook makes auto-request to a server, but I need to make that request only during certain condition. I tried to implement it according to Redux documentation: (https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching), but it didn't work out.

My implementation: (src/features/posts/PostList.js)

import React, { useState } from 'react'
import { useGetPostsQuery } from '../api/apiSlice'

const PostExcerpt = ({ post }) => {
    return (
        <div>
            <p>{post.postText}</p>
            <p>
                <small>{post.author}</small>
            </p>
        </div>
    )
}

export const PostList = () => {
    const [skip, setSkip] = useState(true)
    const { data: posts = [], isLoading, isSuccess, isError, error } = useGetPostsQuery({ skip })

    let content

    if (isLoading) {
        content = <h3>Posts Loading ...</h3>
    } else if (isSuccess) {
        content = posts.map(post => <PostExcerpt key={post.id} post={post} />)
    } else if (isError) {
        content = (
            <div>
                <h3>Error happened</h3>
                <p>
                    <small>{error.toString()}</small>
                </p>
            </div>
        )
    }

    return (
        <div style={{ border: '2px solid red' }}>
            <h2>Posts:</h2>
            <button onClick={() => setSkip(prev => !prev)}>Fetch it</button>
            {content}
        </div>
    )
}

According to Redux Toolkit RTK Query documentation, I should have utilized an object with a boolean skip property in it as an argument for an auto-generated hook. I did, but it didn't work out. It has been anyway making a request to the server. So, what have I been doing wrong?

apiSlice looks like: (src/features/api/apiSlice.js )

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

// Define our single API slice object
export const apiSlice = createApi({
    // The cache reducer expects to be added at `state.api` (already default - this is optional)
    reducerPath: 'api',
    // All of our requests will have URLs starting with '/fakeApi'
    baseQuery: fetchBaseQuery({ baseUrl: '/fakeApi' }),
    // The "endpoints" represent operations and requests for this server
    endpoints: builder => ({
        // The `getPosts` endpoint is a "query" operation that returns data
        getPosts: builder.query({
            // The URL for the request is '/fakeApi/posts'
            query: () => '/posts',
        }),
        addNewPost: builder.mutation({
            query: initialPost => ({
                url: '/posts',
                method: 'POST',
                body: initialPost,
            }),
        }),
    }),
})

// Export the auto-generated hook for the `getPosts` query endpoint
export const { useGetPostsQuery, useAddNewPostMutation } = apiSlice

You also may check this code out on GitHub. GitHub link:https://github.com/AlexKor-5/Redux_Mock_Service_Worker/tree/bd593191dce8c13982ffa2cdb946046d6eb26941


Solution

  • Options are always the second argument - you need to do

    useGetPostsQuery(undefined, { skip })