blog
contact
hire me

How to pass parameters to useQuery using Axios

react-query

There are two ‘correct’ ways to pass parameters to useQuery using Axios and one “looks and feels” cleaner than the other.

Method 1: Destructuring

The query function that is passed to useQuery is given a context object. On this object, we have a queryKey. This contains the parameter that you’re passing to the function. We destructure the context object to get the queryKey and destructure that array to get the param we’re passing [_, userId] = queryKey

const fetchPosts = ({ queryKey }) => {
  const [_, userId] = queryKey;
  const { data } = axios.get(`https://yourapiroute.com/posts/${userId}`);
  return data;
};
const { data } = useQuery(["posts", userId], fetchPosts);

Method 2: Anonymous functions (my go-to)

We’re passing exactly what we need using an anonymous function. It’s easier to read and reason about. We know what’s being passed without searching for the function in question and checking what is being destructured and how.

const fetchPosts = (userId) => {
  const { data } = axios.get(`https://yourapi.com/posts/${userId}`);
  return data;
};
const { data } = useQuery(["posts", userId], () => fetchPosts(userId));