GraphQL Filter Data with Variables

I am trying to filter some data in a NextJS app using GraphQL but am quite new to GraphQL and need some help. My query works as I tested it on my repo/graphql page but not sure how to integrate it or how to use variables.

const productQuery = `
query GetFilteredProducts($product_type: String, $style: String, $colour: String, $size: String) {
 allProducts(where: {
    product_type: $product_type
    styles: {style: $style},
    colours: {colour: $colour},
    sizes: {size: $size}
  }) {
    edges {
      node {
        title
        description
        images {
          position
          colour
          image
        }
      }
    }
  }
}
`;

const getProducts = async ({ previewData, queryKey }) => {
	const client = createClient({ previewData });

	const productType = queryKey[1].productType;
	const style = queryKey[1].style;
	const colour = queryKey[1].colour;
	const size = queryKey[1].size;

	// I'm not sure how to use graphQl or how I send the variables above to be used by my query.
const filteredProducts = await client.get({ graphQuery: productQuery });

	console.log(filteredProducts);

	return filteredProducts;
};

I have also noticed I am getting a CORS error.

Hi @rsheppard83, thanks for reaching out.

If your queries work in the /graphql playground you already have half of the query ready. The next thing to make variables work is to make the queries dynamic. It depends on the type of action that triggers them. What action do you want to achieve with this query?

1 Like

The getProducts function is called by React Query in my page component. It is called every time a user changes a filter option on the page and it should send back the relevant products.

The filters are Type, Style, Colour and Size which is already setup.

Ok, I see. So maybe the problem is that these values not getting passed to the query properly. Here's our starter with GraphQL so you can check an example of how this can be made: