Evgeny Alekseev
Evgeny Alekseev

Reputation: 185

Cannot call useQuery inside event handler (react-query, react-hook-form)

I have to call useQuery inside event handler. (user registration) and Im trying something like this.

const [postUser, { isError, isLoading, data }] = useQuery('user', () =>
    axios.post(API_URL, { query: GET_TOKEN_QUERY }).then((res) => res.data)
  )

  const openModalCallback = React.useCallback(
    (modalName) => {
      onOpenModal(modalName)
    },
    [onOpenModal]
  )

  async function onSubmit(data: LoginInputs) {
    if (data.checkbox) {
      postUser()
    }
  }

But I get an error like this and cant resolve it. Help me please.enter image description here

Upvotes: 0

Views: 1619

Answers (2)

Nouman Ahmad
Nouman Ahmad

Reputation: 1

You cannot simply post the data with the useQuery hook, for that you have to use the useMutation() hook and it returns a function which you can call inside an event handler.

Upvotes: 0

hendra
hendra

Reputation: 2651

If you want to create/update/delete data or perform server side-effects (opposed to just read data from server), better use useMutation.

The hook returns a mutate() function which you can call onSubmit().

Upvotes: 1

Related Questions