Search code examples
reactjsredux-toolkitrtk-query

RTK Query how to update query state


I have a route where i fetch all categories

getAllCategoriesAdmin: builder.query({
       query: () => 'categories/allAdmin',
       providesTags: ['CategoriesAdmin']
    })

Then I get categories data from data refactored part of useGetAllCategoriesAdminQuery

const { isLoading, isError, data = {} } = useGetAllCategoriesAdminQuery();

Now I want to implement search field where I want to update that data part with new data in other words when I create new route

getAllCategoriesAdminSearch: builder.query({
        query: () => 'categories/allAdminSearch',
        providesTags: ['CategoriesAdmin'],
    })

Is there any way that I can reupdate data part from useGetAllCategoriesAdminQuery so I dont have to make another data from useGetAllCategoriesAdminSearchQuery

const { data = {} } = useGetAllCategoriesAdminSearchQuery();


Solution

  • I don't get your question completely but I'm assuming you have a query API and you need the search query for this API. I hope this helps you.

    there are many ways to re-fetch the data:

    1: I think your API should support some query params for searches like this:

    getAllCategoriesAdmin: builder.query({
           query: (searchInput) => `categories/allAdmin/?search=${searchInput}`,
           providesTags: ['CategoriesAdmin']
        })
    

    RTK query creates a cache key base on query URL and params so if you change the search input it will automatically create a new request and fetch the data.

    2: another way is using invalidateTags for example if you have a mutaion query you can invalidate the tags in this case CategoriesAdmin and that causes the RTK clear the cache for corresponding query and refech the data.

    3: refetch function. every useHookQuery in RTK has a re-fetch function that you can assign it to your search event for re-fetching the new data.

    const { refetch, isLoading, isError, data = {} } = useGetAllCategoriesAdminQuery();