DEV Community

Cover image for How to pass parameters to useQuery using Axios
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

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 destructure 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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay