const getSurvey = useQuery(["survey"], () =>
getSurveyData({
page: 1,
userLangCode: langCode,
sortColumnName: "Date",
sortColumnOrder: "DESC",
country,
ip,
})
);
I am trying to run the query after a certain event takes place but it gets called as soon as the component loads and give me undesirable results though after a while when component gets updated, it just works fine . Since I cannot be bounded in side a function. I need a method where I can use it from ouside the component vut the problem is I cannot use useQuery from outside.
CodePudding user response:
You can tell the query to start disabled and then manually fetch the data later with refetch
:
function SuperAwesomeComponent() {
const getSurvey = useQuery(["survey"], () =>
getSurveyData({
page: 1,
userLangCode: langCode,
sortColumnName: "Date",
sortColumnOrder: "DESC",
country,
ip,
}), {
enabled: false
}
);
const someEventHandler = () => {
getSurvey.refresh();
}
You can set enabled to the value of a prop or state variable to automatically run the query when a condition becomes true
See: https://tanstack.com/query/v4/docs/guides/dependent-queries
CodePudding user response:
query:
const getSurvey = useQuery(
["survey", country],
() =>
getSurveyData({
page: 1,
userLangCode: langCode,
sortColumnName: "Date",
sortColumnOrder: "DESC",
country,
ip,
}),
{
enabled: !!country,
}
);
useEffect
useEffect(() => {
getData();
getSurvey.refetch();
// getSurvey.refresh();
}, [country]);
See: https://tanstack.com/query/v4/docs/guides/dependent-queries