I would like to have a component that show fake data and if the user choose some config it will call the server using 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
My problem is that api.dashboard.getBudgetById.useQuery
is a hook so it can't be in an other hook like useEffect and it's not async too. How I can conditionally call the server ?
Use the
enabled
flag inuseQuery
.https://tanstack.com/query/v4/docs/react/reference/useQuery
Conditionally calling an API using React-Query hook