wp-graphql-tax-query icon indicating copy to clipboard operation
wp-graphql-tax-query copied to clipboard

Variable and Combined Query example.

Open BartoszLobejko opened this issue 5 years ago • 0 comments

Hey, I was struggling to combine few queries together to do more advanced filtering and I found that Directives doesn't work. So I came up with this simple solution to combine tax and meta queries but only include them when needed. Hopefully, that improves performance. (this example also include pagination and fragments)

const ACCOMMODATION_QUERY = (
  first,
  after,
  locationFilter,
  typeFilter,
  ifLocation,
  ifType,
) => gql`
    query AccommodationsQuery(
      $first: Int = ${first}
      $after: String = ${after}
      ${ifLocation ? `$locationFilter: String = "${locationFilter}"` : ``}
      ${ifType ? `$typeFilter: [String] = ["${typeFilter.join('","')}"]` : ``}
    ) {
    accommodations(
      first: $first
      after: $after
      where: {
        orderby: { field: MODIFIED, order: DESC }
        ${
          ifLocation
            ? `metaQuery: {
          metaArray: [{ key: "location", value: $locationFilter, compare: LIKE }]
        }`
            : ``
        }
        ${
          ifType
            ? `taxQuery: {
          taxArray: [
            {
              terms: $typeFilter
              taxonomy: ACCOMMODATIONTYPE
              operator: IN
              field: SLUG
            }
          ]
        }`
            : ``
        }
      }
    ) {
      pageInfo {
        hasNextPage
        endCursor
      }
      edges {
        cursor
        node {
          date
          modified
          slug
          title
          accommodationDetails {
            ...AccommodationListDetails
          }
        }
      }
    }
  }
  ${AccommodationListDetailsFragment}
`;

And then you can skip variables in render

<Query
              query={ACCOMMODATION_QUERY(
                first,
                after,
                locationFilter,
                typeFilter,
                ifLocation,
                ifType,
              )}
              variables={{}}
            >
...
</Query>

Let me know what do you think.

BartoszLobejko avatar Jun 04 '19 02:06 BartoszLobejko