How to pass parameters to useQuery using Axios

How to pass parameters to useQuery using Axios

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 destrucre that array to get the param we're passing [_, userId] = queryKey

I'm not a fan of this one simply because of the _ being used to discard a non-needed item from array destructuring. It feels messy and non-explicit.

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));