1

I need to pass a couple of arguments in a react query one of which needs to decided by the user action

Here is how the query looks so far:

const { refetch: likeDislikeProfile } = useQuery(
  ['like_dislike_profile'], 
  () => like_dislike_profile_q(data.userid, <BOOLEAN_ARG>), // 👈 
  { enabled: false }
)

Whenever the clicks on a like/dislike button, the argument will be true/false respectively.

This is further used as a query param in the request : action?like=false

How do I achieve this?

My approach

  • create a local state that changes on button click
  • create a side effect (useEffect) method which is triggered when this state changes
  • which will further trigger this react query

This approach seems bad, can't think of anything else atm

1 Answer 1

2

Looks like your HTTP request is changing data in the backend, that's the use case for mutations.

From the official docs

A query is a declarative dependency on an asynchronous source of data that is tied to a unique key. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using Mutations instead.

For your use case it should be something like this

const updateLike = useMutation((id, bool) => like_dislike_profile_q(id, bool))

// invoke the mutation at any point like this
updateLike.mutate('my-id', true)

Read more about mutations on Tkdodo's blog post on mutations

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this, I had no idea this existed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.