Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

useQuery (with refetch) or useMutation for hitting a validation api? #7627

Unanswered
Laurence-NZ asked this question in Q&A
Discussion options

Hello, I have a form input which takes a license key and a button which fires a POST request to validate the key.

  • This is all contained within one react component.
  • This API simple sends the key to the server to VALIDATE that the license key is correct.
  • Its a POST request which returns true or false.
  • It has not side effects and it does not make any changes.
  • I expect the user to trigger this validation request once and as many times as they like (only the last call should trigger a callback toast though)
  • I do not expect react query to 'auto refire'.
  • The server can change it's mind at any time so the results should not be cached.

I have found a few different approaches online... I would really appreciate some advice on best practices!

Approach One - useQuery

  • Set Enabled to false
  • Pass the props (the license) as a query key and store it/update it with useState
  • Call refire on button click

Approach Two - useMutation

  • Just pass the license key as a prop with onMutate

Mutate is easier but the name implies a change which is not happening. It also cannot be aborted as easily by passing signal. I would like to pop a valid/invalid toast when the mutation completes.

EDIT: Also would like to do other things which react query is good for, such as showing loading spinner or utilizing the built in error handling for determining if an error occurred

You must be logged in to vote

Replies: 2 comments 1 reply

Comment options

Approach 3:

<button onClick={() => {
 fetch('/validate').then(showValidToast).catch(showInvalidToast)
}}

🤷‍♂️

You must be logged in to vote
1 reply
Comment options

Thanks for the response. This was actually approach 0 😆 but we would still like to utilize react query for it's easy async state management - so we can display a loading spinners etc.

Both of the previous two approaches 'work' - but I guess this use case isn't something that is a perfect fit for what react query offers?

Comment options

I use TanStack Form.

Does someone have a better answer? I have a simple form with a phone number input and I try to check if a phone number is already used asynchronously. Unfortunately I can't have fetch() because I use tRPC and onChangeAsync validator doesn't work because the query doesn't have data on time (obv)

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /