Search code examples
graphqlreact-apollogqlhasura

Can I make variables optional in a GraphQL query?


I have a query that includes a variable $filter which is a string.

This variable is only relevant if the user has said they want to filter the results. If user doesn't filter, I want all results back that meet the criteria.

Is there a way to omit the filter variable in this query? I've tried passing null and I get an error.

const NOTIFY_NEW_PUBLIC_FEELINGS = gql`
  subscription notifyNewPublicFeelings($page_id: uuid!, $filter: String!) {
    feelings(
      where: { is_public: { _eq: true }, page_id: {_eq: $page_id}, feeling: {_eq: $filter} }
      limit: 1
      order_by: { created_at: desc }
    ) {
      id
      created_at
    }
  }
`;

Solution

  • The problem is that you've marked $filter as String! (! indicates non-nullable). So, necessarily, passing null is going to cause an issue. If you mark string as nullable (just String, without the !), you can pass null safely.