当点击按钮获取数据时,之前的数据/错误没有被清除。 正在附加新数据。我在反应查询中尝试了各种选项,但没有一个解决我的问题。
使用的版本> @tanstack/react-query: "5.52.2"
import { useQuery } from "@tanstack/react-query";
import React from "react";
import { mockAPICall } from "./helper/mockAPICall";
const FetchQuery = () => {
const { data, error, refetch, isFetching } = useQuery({
queryKey: ["repoData"],
queryFn: mockAPICall,
enabled: false,
retry: false,
});
const clicked = () => {
refetch();
};
return (
<div>
<button
className="flex m-auto border-solid border-black px-7 py-3 border-2 hover:border-gray-400 active:text-gray-400"
onClick={clicked}
>
React Query
</button>
<div className="py-3 flex m-auto justify-center">
{isFetching && (
<div className="text-slate-400">{"Loading..."}</div>
)}
{data && <div className="text-green-500">{data}</div>}
{error && <div className="text-red-500">{error}</div>}
</div>
</div>
);
};
export default FetchQuery;
和mockAPI代码如下
export const mockAPICall = () => {
const randomNum = Math.floor(Math.random() * (100 - 0));
console.log("🚀 > mockAPICall > randomNum:", randomNum);
return new Promise((res, rej) => {
setTimeout(() => {
if (randomNum < 50) {
res("Successful Response "+ randomNum);
console.log("success");
} else {
rej("Intended Err "+ randomNum);
console.log("fail");
}
}, 1000);
});
};
我正在下面上传 GIF 来向您展示我所面临的情况
通过在 refetch() 之前使用
queryClient.resetQueries(['repoData'])
解决