2

I am working on a React JS project. I am using React Hooks (functional components) and React query.

I normally run/ execute the query as follow in the functional component.

const ItemList = (props) => {
  let getItemsQuery = useQuery([ 'get-items' ], getItems, {
    retry: false,
    refetchOnWindowFocus: false
  });

  // The rest of the code goes here
}

Basically the query is executed when the component is loaded so that the API call is made too.

Now, I am looking for a way where I can only execute the query when a button is clicked.

return (
   <button onClick={() => {
       //make the call. The value or value might be overridden when the API call is made when the Call 2 button is clicked
    }}>Call 1</button>
   <button onClick={() => {
       //make the call. The value or value might be overridden when the API call is made when the Call 1 button is clicked
    }}>Call 2</button>
)

As you can see in the dummy code above, the comment explains what I want to achieve. How can I do that?

yudhiesh
  • 6,383
  • 3
  • 16
  • 49
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

6

Pulling from this answer:

import React, { useState } from "react";
import { useQuery } from "react-query";

const App = (props) => {
  const [text, setText] = useState("");

  // use your async request (axios, fetch, etc)
  // useQuery expects a Promise so we can safely use this instead
  const emulateFetch = async (_) => {
    // axios.get (...)
    console.log(`Passing ${text} to fetch`);
    return new Promise((resolve) => {
      resolve([{ data: "ok" }]);
    });
  };

  const handleClick = () => {
    // manually refetch
    refetch();
  };

  const { isLoading, error, data, refetch } = useQuery(
    ["key", { text }],
    emulateFetch,
    {
      refetchOnWindowFocus: false,
      enabled: false // needed to handle refetchs manually
    }
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <p>Home page</p>
      <input
        type="text"
        value={text}
        onChange={(event) => setText(event.target.value)}
      />
      <button onClick={handleClick}>Click me</button>
      {JSON.stringify(data)}
    </div>
  );
};

export default App;

Working sandbox.

jack.benson
  • 2,211
  • 2
  • 9
  • 17