'Prevent Caching on a specific RTK Query Endpoint

I am using rtq query and i have an endpoint that takes azure-ad oid from the global store and makes a query to the backend to check if the user exists on the backend to check if the user exists. If the user exists then I redirect the user to the dashboard else I do not redirect the user.

The problem is that despite trying to prevent caching on that endpoint, it still uses the cached data and by the time the real data comes from the server, the redirect has already happened. Below are some of the steps I have taken to prevent this from happening.

  1. Using refetch
  2. Setting refetchOnMountOrArgChange: true,
  3. Setting keepUnusedDataFor: 0.0001 to invalidate the cache almost immediately

The point is that I do not want this endpoint to use any cached data.

Below is my component:

 const [isSignedIn] = useIsSignedIn();
  const history = useHistory();
  const dispatch = useAppDispatch();
  const ongraphLogin = async (role: string) => {
    if (Providers.globalProvider.login) {
      dispatch(setloginType(role));

      await Providers.globalProvider.login();
    }
  };
  const userState = useAppSelector(state => state.userState);

 
  console.log(userState?.currentUser?.id);
  const { data, error, isLoading, refetch } = useGetUserByOidQuery(userState?.currentUser?.id, {
    skip: isSignedIn,
    refetchOnMountOrArgChange: true
  });
  
  useEffect(() => {
    refetch();
    // console.log(res);
    if (isSignedIn) {
      console.log('I am in');
      // Check if the user exists in the ndovysystem
      if (data?.status === 'success') {
        console.log(data);
        history.push('/user');
      } else if (userState.loginType === 'volunteerRegistration') {
        history.push('/register/volunteer');
      } else if (userState.loginType === 'menteeRegistration') {
        history.push('/register/mentee');
      }
    }
  }, [isSignedIn, data]);

Below is the endpoint

import { ndovuAPI } from './ndovuAPI';

export const ndovuUserAPI = ndovuAPI.injectEndpoints({
  endpoints: builder => ({
    getUserByOid: builder.query({
      query: (oid: string) => `/users/oid/${oid}`,
      keepUnusedDataFor: 0.0001
    })
  })
});

// Export hooks for usage in functional components
export const { useGetUserByOidQuery} = ndovuUserAPI;

Kindly help me solve this.



Solution 1:[1]

You can pass timestamp as an argument of the query. That's what I did to prevent caching on mounting of the component.

Like this

const timestampRef = useRef(Date.now()).current;
const {data = [], isFetching} 
    = useGetChatMessagesQuery({id: chatId, lastMessageId, sessionId: timestampRef});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akmed0zmey