防止在特定 RTK 查询端点上进行缓存

Dij*_*lex 10 reactjs redux rtk-query

我正在使用 rtq 查询,并且有一个端点,该端点从全局存储中获取 azure-ad oid 并向后端进行查询以检查用户是否存在于后端以检查用户是否存在。如果用户存在,那么我将用户重定向到仪表板,否则我不会重定向用户。

问题在于,尽管尝试阻止该端点上的缓存,但它仍然使用缓存的数据,并且当真实数据来自服务器时,重定向已经发生。以下是我为防止这种情况发生而采取的一些步骤。

  1. 使用重新获取
  2. 设置 refetchOnMountOrArgChange: true,
  3. 设置 keepUnusedDataFor: 0.0001 几乎立即使缓存失效

关键是我不希望这个端点使用任何缓存的数据。

以下是我的组件:

 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]);
Run Code Online (Sandbox Code Playgroud)

下面是端点

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;
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题。

akm*_*mey 11

您可以将时间戳作为查询的参数传递。这就是我为防止组件安装时缓存所做的事情。

像这样

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


phr*_*hry 9

唔。您无法真正阻止查询的缓存,但您可以将其作为突变 - 默认情况下,即使具有相同参数的两个突变也不会共享缓存条目。

  • @DanielprabhakaranN 因为 RTK 查询的全部目的是缓存数据,我想正确的答案最终是只使用“fetch”。您无法规避核心功能。 (2认同)