Home > Net >  Redux RTK Query seems not caching requests
Redux RTK Query seems not caching requests

Time:09-06

I'm calling the RTK-Query lazy hook from two different components with the same parameter.

github.api.ts

    export const githubApi = createApi({
      reducerPath: "github/api",
      baseQuery: fetchBaseQuery({
        baseUrl: "https://api.github.com/"
      }),
      endpoints: build => ({
        
        getUserRepos: build.query<IRepo[], string>({
          query: (username: string) => ({
            url: `users/${username}/repos`
          })
        })
      }),
      refetchOnFocus: true,
    })

    export const {
      useLazyGetUserReposQuery
    } = githubApi

store.index.ts

    export const store = configureStore({
      reducer: {
        [githubApi.reducerPath]: githubApi.reducer,
      },
      middleware: (getDefaultMiddleware) => 
    getDefaultMiddleware().concat(githubApi.middleware)
    })

So in my first component I call it like this:

    const [fetchRepos, { isFetching: areReposLoading, data: repos }] = useLazyGetUserReposQuery()

    fetchRepos(`sss`)

Then I change location (unload first component and switch to another component) And in the second (another) component I call the same hook with the same parameter (string sss) but instead giving me the cached value the RTK-Query fires another request and gives me the same data back, but not from cache.. enter image description here

Here's the link to the entire src code: github.rtk.query.app

CodePudding user response:

If you use useLazyQuery, you have to indicate to the trigger function that you actually want to use the cache value and not start a new request to the server:

    fetchRepos(`sss`, true)
  • Related