-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
useQuery (with refetch) or useMutation for hitting a validation api? #7627
-
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
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 1 reply
-
Approach 3:
<button onClick={() => {
fetch('/validate').then(showValidToast).catch(showInvalidToast)
}}
🤷♂️
Beta Was this translation helpful? Give feedback.
All reactions
-
😕 1
-
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?
Beta Was this translation helpful? Give feedback.
All reactions
-
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)
Beta Was this translation helpful? Give feedback.