0

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?

KwehDev
  • 261
  • 1
  • 3
  • 14
  • I'm not sure I follow. Do you mean you are deleting the user on the server? – phry Feb 19 '22 at 16:01
  • @phry Apologies, I was in a bit of a rush. I've edited the question, hopefully that provides more insight. – KwehDev Feb 20 '22 at 11:19

1 Answers1

1

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)
phry
  • 35,762
  • 5
  • 67
  • 81