kinzito17
kinzito17

Reputation: 300

GraphQL query how to pass variables

Hi all I have a query where I am trying to get messages from a user with a specific uuid or a role that matches the users role. I am unsure of how to properly use the _ilike or % in this instance. I've tried a myriad of combinations yet the role messages never get returned. My query as it sits now and the hook used in the component are below.

I appreciate any feedback.

Here is my query

query getUserMessages($userId: String!) {
  messageReceivers(
    where: { _or: [{ userId: { _eq: $userId } }, { message: { roles: { _ilike: "%" } } }] }
  ) {
    messageId
    userId
    message {
      id
      audioLink
      body
      videoLink
      user {
        firstName
        lastName
        photo
        title
        specialty
        profession
        location
      }
    }
  }
}

Using the lazyquery hook in component

  const [getUserMessages, { error, called, loading, data }] = useGetUserMessagesLazyQuery()
  const userRole = `%${user.role}%`

  useEffect(() => {
    getUserMessages({
      variables: { userId: user?.id, message: { roles: { _ilike: userRole } } },
    })
  }, [user])

Upvotes: 0

Views: 3575

Answers (2)

kinzito17
kinzito17

Reputation: 300

Thanks @fedonev! Though I didn't see your solution you were absolutely correct. I was able to work it out a little differently and I hope this helps someone who's run into the same issue.

By creating the variable $role in the query I was able to use the same syntax as was being used by the userId variable. If anyone has this issue please feel free to comment I will happily help if I can.

Query

query getUserMessages($userId: String!, $role: String = "%") {
  messages(
    where: {
      _or: [{ roles: { _ilike: $role } }, { messageReceivers: { userId: { _eq: $userId } } }]
    }
    order_by: { createdAt: desc }
  ) {
    createdAt
    id
    body
    audioLink
    videoLink
    roles
}

Call from in component

useEffect(() => {
    getUserMessages({
      variables: { userId: user?.id, role: user?.role },
    })
  }, [user])

Upvotes: 0

fedonev
fedonev

Reputation: 25639

You are incorrectly passing userRole to the query. To fix it, apply userId's pattern to userRole.

  1. In the query definition, add $userRole in the operation signature (You are currently hardcoding _ilike to % in the query, but you want set it dynamically as $userRole).
  2. In the calling function, send the variables correctly variables: { userId: user?.id, userRole: userRole}.

The GraphQL Variable docs neatly describe how this fits together.

Upvotes: 1

Related Questions