#Enable query on click and get updated data in same function

4 messages · Page 1 of 1 (latest)

last warren
#
  const { data, refetch, isFetching } = useQuery({
    queryKey: ["todos"],
    queryFn: async () => {
      const res = await fetch("https://jsonplaceholder.typicode.com/todos");
      const data = await res.json();
      return data;
    },
    enabled: false
  });
  const handleClick = async () => {
    await refetch();
    if (data) {
      alert(data[0].title);
    }
  };
#

how can I get data in after refetch

cunning geode
#

refetch return type is Promise<UseQueryResult>. So you can do:

const result = await refetch();
if (result.data) {
  alert(result.data[0].title);
}

I don't know what the end goal is but instead of calling refetch() I would probably look into setting enabled to true and using the data returned by useQuery though.