新用户登录时RTK Query未拉取最新数据,返回缓存数据求助
RTK Query新用户登录返回缓存数据问题
新用户登录时,RTK Query未拉取最新数据,反而返回缓存数据。使用的依赖版本为@reduxjs/toolkit": "^1.9.5"。
相关API定义代码
export const presentationApi = createApi({ reducerPath: "vsl/api/v1", baseQuery: fetchBaseQuery({ baseUrl: BASE_URL, prepareHeaders: (headers) => { const token = localStorage.getItem("token"); if (token) { const { exp }: { exp: number } = decode(token); // token has expired if (exp * 1000 < new Date().getTime()) { localStorage.clear(); } else { headers.set("Authorization", `Bearer ${token}`); } } return headers; }, }), // AUTH ENDPOINTS signin: builder.mutation<any, Partial<any>>({ query: (body) => ({ url: `/auth/login`, method: "POST", body, providesTags: ["Auth"], }), }), signout: builder.mutation<any, undefined>({ query: () => ({ url: `/auth/logout`, method: "POST", invalidatesTags: ["Auth", "Presentations"], }), }), // PRESENTATION ENDPOINTS getAllPresentations: builder.query({ query: () => ({ url: `/presentation`, method: "GET", cache: "no-cache", providesTags: ["Presentations"], }), }), });
登出逻辑相关代码
const [signout, { data: response, isLoading, isError, isSuccess }] = useSignoutMutation(); const signingOutRef = React.useRef<boolean>(false); const handleLogout = async () => { localStorage.removeItem("token"); console.log("Before purge:", store.getState()); // await persistor.purge(); // await persistor.purge(); // await persistor.purge(); // persistor.flush(); // console.log("After purge:", store.getState()); // console.log('logout response',response); signingOutRef.current = true; signout(undefined); }; useEffect(() => { if (signingOutRef.current) { if (isLoading) { notifyLoading("Wait!", "Logging out..."); } if (isSuccess) { dismissNotifyAll(); // navigate("/auth/signin"); window.location.href = "/auth/signin"; makeRefFalse(); } if (isError) { dismissNotifyAll(); notifyWarning("Oops!", "Something went wrong. Please try again."); makeRefFalse(); } } }, [isLoading, isError, isSuccess, navigate, signingOutRef.current]); // had to use it that way. otherwise it was not working const makeRefFalse = () => signingOutRef.current ? (signingOutRef.current = false) : false;
已尝试的解决措施
- 最初未使用登出API,后来为让RTK Query失效
Presentations标签添加了该API,但无效果 - 尝试调用
persistor.purge()也无法解决问题 - 目前只能通过
window.location.href强制刷新页面规避问题
若需远程协助,可安排远程会话,希望得到解决方案。
内容的提问来源于stack exchange,提问作者Mutahhir Khan
相关产品推荐
相关产品推荐

