Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to run tanstack react query from outside of the component since I cannot use useQuery there?

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.

like image 414
Alish Madhukar Avatar asked Oct 21 '25 03:10

Alish Madhukar


1 Answers

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.refetch();
  }

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

like image 167
coagmano Avatar answered Oct 23 '25 17:10

coagmano