How to avoid refetching when using reduxToolkit rtk

Viewed 48

Hi all I have following code. I am new in reduxToolkit rtk and hope you can help to find solution to my question.

I have following code. So with this code I am creating posts endpoint.

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

    export const postsApi = createApi({
    reducerPath: "postsApi",
    baseQuery: fetchBaseQuery({
    baseUrl: "https://jsonplaceholder.typicode.com/",
     }),
    endpoints: (builder) => ({
    posts: builder.query({ query: () => "/posts" }),
    }),
    });

    export const { usePostsQuery } = postsApi;

This is my store.

    import { configureStore } from "@reduxjs/toolkit";
    import { postsApi } from "./services/postsApi";

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

And this is where I am getting my data.

    const Home = () => {
      const count = useSelector(
        (state) => state?.postsApi?.queries?.["posts(undefined)"]?.data
      );

      const { data, error, isLoading, isFetching, isSuccess } = usePostsQuery();

      return (
        <>
          {isSuccess && console.log("data", data)} 
        </>
      );
    };

    export default Home;

So when I am fetching the data, it stored in store , so after every time when <Home /> component is mounting I am again fetching that data from backend, I want to avoid that fetching because I already have that data my store. How can do that ?

2 Answers

There should not be such refetching happening - is this an assumption you have or are you really seeing that in the network tab?

By default, if trigger the same query as an existing one, no request will be performed.

If you need, you can force a refetch. You can call refetch that is returned by the hook.

You can find more details on RTK Queries Docs

Related