0

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?

  • _"cannot use [useMutation](https://tanstack.com/query/v4/docs/guides/mutations)"_... why not, that's literally what it's for? – Phil Sep 06 '22 at 06:47
  • @Phil, yes man, I wanted to but now I am working on a legacy application where I have to use this pattern. – Anandu Babu Sep 06 '22 at 06:49
  • That doesn't really answer my question. If you're limited to a particular version of react-query, please make that clear in your question – Phil Sep 06 '22 at 06:50
  • The version is 3 – Anandu Babu Sep 06 '22 at 06:51
  • How have you verified that the problem is what you think it is? If you're seeing empty data posted, I've got a duplicate link that explains why – Phil Sep 06 '22 at 06:52
  • You have to do use Mutation https://tanstack.com/query/v4/docs/guides/mutations – man.in.the.jukebox Sep 06 '22 at 06:52
  • Also, v3 has `useMutation` so it's really not clear why you cannot use it ~ https://react-query-v3.tanstack.com/reference/useMutation#_top – Phil Sep 06 '22 at 06:55
  • TL;DR of the duplicate, you should have something like `useEffect(() => { if (currentPost) refetch(); }, [currentPost])` – Phil Sep 06 '22 at 06:56

0 Answers0