TanStackT
TanStack2y ago
6 replies
cold-orange

How to run dynamic Query in Tanstack Query?

0

I've been having a rough time understanding tanstack/query. I'm trying to fetch data using tanstack.

What I'm trying to get is store the data in my state, and then when I press the button, it will pass to my URL and then it will call the button.
  const [data, setData] = useState({
    from: "",
    end: "",
    year: "",
    college: "",
    type: "",
  });

  const handleClick = () => {
    
  };

This is my sample URL.

http://localhost:5000/api/result?from=8&end=10&year=23&college=CEIS&type=Students

This is my apicall
export const getUsers = async (from, end, year, college , type) => {
  try {
    const response = await axios.get(`http://localhost:5000/api/result?from=${from}&end=${end}&year=${year}&college=${college}&type=${type}`)
    return response.data;
  } catch (error) {
    // Handle errors here if needed
    throw error;
  }
};

And this is my getResult
export const resultQuery = () => {
  const {isPending, error, data ,isFetching} = useQuery({
    queryKey: ["users", data.from, data.end, data.year, data.college, data.type],
    queryFn:  () => getUsers(data.from, data.end, data.year, data.college, data.type)
  })

  return { isPending, error, data, isFetching };
}



So what i'm trying to do is only get the data once the button is click, is that possible in tanstack/react-query 5?
Was this page helpful?