在新用户登录时,RTK Query未获取到最新数据,而是返回了缓存的数据。

huangapple go评论66阅读模式
英文:

on new user login, RTK Query not fetching the latest data, instead returning cached data

问题

以下是翻译好的部分:

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"],
		}),
	}),
});

using "@reduxjs/toolkit": "^1.9.5",

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 taht way. otherwise it was not working
const makeRefFalse = () => signingOutRef.current ? (signingOutRef.current = false) : false;

had to deliberately reload the page with window.location.href. not even the persistor.purge working.
first i was not using the logout api, but then i had to make it so that rtk query can invalidate the Presentation tag. but turns out to don't have any impact and success.
If any of you guy wants to come at the remote session i can do that.

希望这有助于你的工作!

英文:
    export const presentationApi = createApi({
reducerPath: &quot;vsl/api/v1&quot;,
baseQuery: fetchBaseQuery({
baseUrl: BASE_URL,
prepareHeaders: (headers) =&gt; {
const token = localStorage.getItem(&quot;token&quot;);
if (token) {
const { exp }: { exp: number } = decode(token);
//token has expired
if (exp * 1000 &lt; new Date().getTime()) {
localStorage.clear();
} else {
headers.set(&quot;Authorization&quot;, `Bearer ${token}`);
}
}
return headers;
},
}),
// AUTH ENDPOINTS
signin: builder.mutation&lt;any, Partial&lt;any&gt;&gt;({
query: (body) =&gt; ({
url: `/auth/login`,
method: &quot;POST&quot;,
body,
providesTags: [&quot;Auth&quot;],
}),
}),
signout: builder.mutation&lt;any, undefined&gt;({
query: () =&gt; ({
url: `/auth/logout`,
method: &quot;POST&quot;,
invalidatesTags: [&quot;Auth&quot;, &quot;Presentations&quot;],
}),
}),
// PRESENTATION ENDPOINTS
getAllPresentations: builder.query({
query: () =&gt; ({
url: `/presentation`,
method: &quot;GET&quot;,
cache: &quot;no-cache&quot;,
providesTags: [&quot;Presentations&quot;],
}),
}),
});

using "@reduxjs/toolkit": "^1.9.5",

   const [signout, { data: response, isLoading, isError, isSuccess }] = useSignoutMutation();
const signingOutRef = React.useRef&lt;boolean&gt;(false);
const handleLogout = async () =&gt; {
localStorage.removeItem(&quot;token&quot;);
console.log(&quot;Before purge:&quot;, store.getState());
// await persistor.purge();
// await persistor.purge();
// await persistor.purge();
// persistor.flush();
// console.log(&quot;After purge:&quot;, store.getState());
// console.log(&#39;logout response&#39;,response);
signingOutRef.current = true;
signout(undefined);
};
useEffect(() =&gt; {
if (signingOutRef.current) {
if (isLoading) {
notifyLoading(&quot;Wait!&quot;, &quot;Logging out...&quot;);
}
if (isSuccess) {
dismissNotifyAll();
// navigate(&quot;/auth/signin&quot;);
window.location.href = &quot;/auth/signin&quot;;
makeRefFalse();
}
if (isError) {
dismissNotifyAll();
notifyWarning(&quot;Oops!&quot;, &quot;Something went wrong. Please try again.&quot;);
makeRefFalse();
}
}
}, [isLoading, isError, isSuccess, navigate, signingOutRef.current]);
//had to use it taht way. otherwise it was not working
const makeRefFalse = () =&gt; signingOutRef.current ? (signingOutRef.current = false) : false;

had to deliberately reload the page with window.location.href. not even the persistor.purge working.
first i was not using the logout api, but then i had to make it so that rtk query can invalidate the Presentation tag. but turns out to don't have any impact and success.
If any of you guy wants to come at the remote session i can do that.

答案1

得分: 1

登录操作不会使您的代码中的标签失效。请将以下代码进行更改:

signin: builder.mutation&lt;any, Partial&lt;any&gt;&gt;({
query: (body) =&gt; ({
url: `/auth/login`,
method: &quot;POST&quot;,
body,
providesTags: [&quot;Auth&quot;],
}),
})

改为
signin: builder.mutation&lt;any, Partial&lt;any&gt;&gt;({
query: (body) =&gt; ({
url: `/auth/login`,
method: &quot;POST&quot;,
body,
invalidatesTags: [&quot;Presentations&quot;],
}),
}),

请注意,呼叫人们进行远程会话并不是适当的行为。
英文:

Signin does not invalidate the tag in your code. Change

    signin: builder.mutation&lt;any, Partial&lt;any&gt;&gt;({
query: (body) =&gt; ({
url: `/auth/login`,
method: &quot;POST&quot;,
body,
providesTags: [&quot;Auth&quot;],
}),
})

with

    signin: builder.mutation&lt;any, Partial&lt;any&gt;&gt;({
query: (body) =&gt; ({
url: `/auth/login`,
method: &quot;POST&quot;,
body,
invalidatesTags: [&quot;Presentations&quot;],
}),
}),

And please note that calling people to a remote session is not an appropriate behaviour.

huangapple
  • 本文由 发表于 2023年6月22日 17:50:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定