skip to Main Content

I’m using useQuery inside a custom hook, called usePostData. this is the custom hook code:

import { useQuery } from "@tanstack/react-query";
import axios from "axios";

const usePostData = (queryKey, endPoint, object) =>
  useQuery(
    [queryKey],
    async () => {
      await axios
        .post("http://localhost:1337" + endPoint, object)
        .then((data) => console.log(data, queryKey))
        .catch((err) => console.log(err));
      return data;
    },
    { enabled: false }
  );

export default usePostData;

I’m calling it on a submit event of a form, like this:

  const { data: response, refetch } = usePostData(
    `postSingularExpense-${Math.random()}`,
    "/api/expences",
    submittedExpense
  );

  const handleSubmitExpense = async (e) => {
    e.preventDefault();
    await refetch();
  };

for some reason, it runs 4 times instead of once and thenm stops with this error message:

error message

why is that and how to correct it?

2

Answers


    • You’re referring to data outside of the function where it exists
    • await axios.post().then() doesn’t make sense. If you’re using await on a function, it will return resolved value so you don’t need .then(). Use async/await or promise syntax, not both 🙂
    const usePostData = (queryKey, endPoint, object) =>
      useQuery(
        [queryKey],
        async () => {
          try {
            const { data } = await axios.post("http://localhost:1337" + endPoint, object);
            console.log(data, queryKey);
            return data;
          }
          catch(err) {
            console.log(err)
          }
        },
        { enabled: false }
      );
    

    Also, I noticed your query key: postSingularExpense-${Math.random()}. What is that? If you want to force a refetch you should’t need to randomize the key.

    useQuery() returns function retry() and includes options like refetchOnMount, refetchInterval etc. You should look into using one of those approaches instead.

    Login or Signup to reply.
  1. The data variable inside your useQuery callback is not defined, (block scope) which leads to the ReferenceError you’re receiving.
    Solve it by removing the await and .then()s 🙂
    You need to capture the response data returned by the POST request and return it from the callback function.

    In addition, you’re generating a random query key for each request, which causes a new query to be created every time. Instead, you should use a better, more stable, query key, such as the endpoint or a unique identifier for the resource you’re posting.

    The updated code is:

    import { useQuery } from "@tanstack/react-query";
    import axios from "axios";
    
    const usePostData = (queryKey, endPoint, object) =>
      useQuery(queryKey, async () => {
        try {
          const { data } = await axios.post("http://localhost:1337" + endPoint, object);
          console.log(data, queryKey);
          return data;
        } catch (error) {
          console.log(error);
          throw error;
        }
      }, { enabled: false });
    
    export default usePostData;
    

    Hope you find this helpful!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search