Karan Kumar
Karan Kumar

Reputation: 3176

How to pass an argument in a React Query?

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

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

Upvotes: 1

Views: 4884

Answers (1)

Gerardo Sabetta
Gerardo Sabetta

Reputation: 559

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

Upvotes: 2

Related Questions