redux-toolkitrtk-query

RTK Query - Delete cache entry if ID is undefined


I have a RTK Query API that fetches a user by ID. This ID is stored in state.

const useUser = () => {
  // This can be a string or undefined.
  const userID = useTSelector((state) => state.users.userId)
  // If the userID above becomes undefined, 
  // for example if it is set from somewhere else
  // then we should clear the result of the below query from the cache.

  const {data: user} = useGetUserByIdQuery(userId)

  return { user } 
}

However, if that ID becomes undefined, I would then like to remove the cached user from the query.

Is this possible out of the box?


Solution

  • You can set skip or use skipToken, which will reset the full hook state and not fire a query.

    import { skipToken } from '@reduxjs/toolkit/query/react'
    
    useGetUserByIdQuery(userId == undefined ? skipToken : userId)