seMikel
seMikel

Reputation: 366

How can I reinitialize a React hook

I have a page where I display the data from the API based on an id. I am using React Query to manage the storage of the data. What I am trying to do is when the input with the id is changed I'd like to refetch the data for a different object. I tried to do the following:

const useData = (id: string) => useQuery(
  ['data', id],
  () => axios.get(`/api/data/${id}`),
  {
    enabled: !!id,
  },
);

const Page = () => {
  const [id, setID] = useState('1');
  const [result, setResult] = useState(useData(id));

  useEffect(() => {
    setResult(useData(id));
  }, [id]);

  return (
    <div>
      {result.data}
      <input onChange={(e) => setID(e.target.value)} />
    </div>
  );
};

But you cannot call hooks inside the useEffect callback. What would be the correct approach for me to reset the result with the data from a new API call?

Upvotes: 0

Views: 757

Answers (1)

TkDodo
TkDodo

Reputation: 28843

react-query will automatically refetch if parts of the query key change. So you are on the right track regarding your custom hook, and for your App, it also becomes much simpler:

const useData = (id: string) => useQuery(
  ['data', id],
  () => axios.get(`/api/data/${id}`),
  {
    enabled: !!id,
  },
);

const Page = () => {
  const [id, setID] = useState('1');
  const result = useData(id);

  return (
    <div>
      {result.data}
      <input onChange={(e) => setID(e.target.value)} />
    </div>
  );
};

that's it. that's all you need.

if id changes, the query key changes, thus giving you a new cache entry, which react-query will fetch for you.

Upvotes: 1

Related Questions