Send post request using useQuery of react query

Viewed 52

I ended up in a situation where I have to send some post requests with react useQuery (cannot use useMutation )

Following is the function used to make the request :

const addNewPost = (newPost) => {
  console.log("Post invoked --- ");
  axios.post(`${baseUrl}/posts`, newPost);
};

This is a custom hook:

const useCreatePost = (postData) => {
  return useQuery(["posts-list", postData], addNewPost(postData), {
    enabled: false,
  });
};

As I am setting enabled to false, I am not expecting any request to be made unless I specify.

In a component I have a form submit which should invoke refetch to manually send the request like this:

export const NewForm = () => {

  const [currentPost, setCurrentPost] = useState();
  const [form] = Form.useForm();
  const { refetch } = useCreatePost(currentPost);

  const onFinish = (values) => {
    values.tags = values.tags.split(",");
    setCurrentPost({ ...values });
    refetch();
    // setCurrentPost(null);
  };
  return (
    <div style={{ padding: "2rem", maxWidth: "600px", textAlign: "center" }}>
      <h1>Create new</h1>
      <br />
      <Form
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 24 }}
        initialValues={
          currentPost && {
            creator: currentPost.creator,
            message: currentPost.message,
            title: currentPost.title,
            tags: currentPost.tags.join(),
          }
        }
        onFinish={onFinish}
      />
 );
};

The problem is even if I don't submit the form the refetch/useCreatePost seems to be invoked! I tried to set the refetch configurations all to false.

How to prevent such auto invoke and restrict the requests only when I want?

Edit: Is there a way to know what react query event triggered the fetch?

0 Answers
Related