Search code examples
javascriptreactjsreact-reduxrtk-query

How to reset Redux toolkit query state (query, not mutation)?


In Redux toolkit query we write as follows in mutations:

const [purchase, { isLoading, isError, isSuccess, reset }] = useCreateOneSaleMutation()

and we can use the reset method to reset the state.

Is there a way I can do the same in the query hooks?

const { isLoading, isError, isSuccess, reset } = useGetOneSale()
  • we can do refetch which actually exists, but I need something to reset these states in a component on call, so I need a reset method.

Is it supported in redux toolkit query?

I depend on isSuccess in a useEffect to render some logic, and I need this isSuccess to reset back to false when the component unmounts.

I have a modal, and when this modal closes, it should reset back to false, because the useEffect looks as follows:

useEffect(()=>{
   switch(true){
      case isSuccess:
        setText('Transaction completed successfully!')
      break
      default:
        setText('Please Enter The client id')
   }
}, [isSuccess])

so there must be something like

useEffect(()=> ()=> reset())

in order for this kind of logic to work.


Solution

  • RTK Query handles this sort of query-resetting through "tags". Check out the docs section on Automated Re-fetching.

    Where you define your API endpoints, you will say that the getOneSale query provides a tag called "OneSale" (or whatever you want to call it). Then say that your createOneSale mutation invalidates that tag.

    const api = createApi({
      baseQuery: /* ... */,
      tagTypes: ['OneSale'],
      endpoints: (build) => ({
        getOneSale: build.query({
          query: /* ... */,
          providesTags: ['OneSale'],
        }),
        createOneSale : build.mutation({
          query: /* ... */,
          invalidatesTags: ['OneSale'],
        }),
      }),
    })
    

    When your useCreateOneSaleMutation execute call succeeds it will invalidate the 'OneSale' tag and RTK will automatically re-fetch any useGetOneSaleQuery hooks.


    If you need to invalidate a tag by some other means (not by a mutation) you can do this by dispatching an invalidateTags action.

    dispatch(api.util.invalidateTags(['OneSale']));