我想有一个组件,显示假数据,如果用户选择一些配置,它会调用服务器使用TRPC:
const { date } = useDateStore();
const [config, setConfig] = useState<configDTO | undefined>(undefined);
const [data, setData] = useState<Budget>(fake);
useEffect(() => {
const fetchData = () => {
try {
if (isDemo || config == undefined) {
setData(fake);
} else {
const response = api.dashboard.getBudgetById.useQuery({
id: config.id,
date: date,
});
if (response.data) {
setData(response.data);
} else {
console.log(response)
}
}
} catch (error) {
// Handle any errors here
console.error("Error fetching data:", error);
}
};
fetchData(); // Call the fetchData function on mount and when config changes
}, [config, date]); // Add date as a dependency if it's needed
字符串
我的问题是api.dashboard.getBudgetById.useQuery
是一个钩子,所以它不能在另一个钩子中,比如useEffect,而且它也不是blog。我如何有条件地调用服务器?
1条答案
按热度按时间fzwojiic1#
在
useQuery
中使用enabled
标志。https://tanstack.com/query/v4/docs/react/reference/useQuery
Conditionally calling an API using React-Query hook的