### Run Local WPGraphQL WooCommerce with Docker Compose Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/testing-quick-start.md This command initiates a local WordPress and WPGraphQL WooCommerce environment using Docker Compose. It scales the 'testing' service to 0 to avoid unnecessary resource usage and starts the 'app' service. Ensure `env.dist` and `codeception.dist.yml` are not modified. ```bash docker-compose up --scale testing=0 app ``` -------------------------------- ### Setup Local WordPress Testing Environment (Bash) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This script copies the distribution environment file to .env and installs the testing environment using Composer. Ensure PHP, MySQL/PostgreSQL, Composer, and WP-CLI are installed. Updates to the .env file may be required based on your machine setup. ```bash cp .env.testing .env composer install-test-env ``` -------------------------------- ### Basic WPUnit Test Class Structure in PHP Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md A foundational PHP class for a WPUnit test using Codeception. It includes setUp() and tearDown() methods for test environment setup and cleanup, and a placeholder testMe() function. ```php assertEquals( array( 5 ), [ 5 ] ); ``` -------------------------------- ### React App Setup with React Router Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md Sets up a basic React application structure using React Router to handle navigation. It defines a root path for the shop page, which will be rendered by the ShopPage component. This snippet is essential for establishing the client-side routing foundation. ```jsx import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import ShopPage from './ShopPage'; function App() { return ( ); } export default App; ``` -------------------------------- ### Example React Component Usage of useCartMutations Hook Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-session-and-using-cart-mutations.md This example demonstrates how to integrate the `useCartMutations` hook within a React component to fetch product data and manage cart interactions. It shows how to set the initial quantity based on `quantityInCart` and trigger add/update/remove actions via the `mutate` function. ```jsx import React, { useEffect, useState } from 'react'; import { useQuery } from '@apollo/client'; import { GetProduct } from './graphql'; const SingleProduct = ({ productId }) => { const [quantity, setQuantity] = useState(1); const { data, loading, error } = useQuery(GetProduct, { variables: { id: productId, idType: 'DATABASE_ID' }, }); const { quantityInCart: inCart, mutate, loading } = useCartMutations(productId); useEffect(() => { if (inCart) { setQuantity(inCart); } }, [inCart]) if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const handleAddOrUpdateAction = async () => { mutate({ quantity }); } const handleRemoveAction = async () => { ``` -------------------------------- ### Fetch Request with Session Header for WPGraphQL Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/configuring-graphql-client-for-user-session.md Demonstrates how to make a POST request to an endpoint using the fetch API, including the 'woocommerce-session' header for WPGraphQL for WooCommerce. The session token is expected to be retrieved from localStorage. This example performs a cart query. ```javascript fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'woocommerce-session': `Session ${sessionToken}`, }, body: JSON.stringify({ query: ` query { cart { contents { nodes { key product { node { id name } } quantity subtotal } } } } `, }), }) .then((response) => response.json()) .then((data) => console.log(data)); ``` -------------------------------- ### Get Product Details GraphQL Query Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-session-and-using-cart-mutations.md Retrieves detailed information about a specific product using its ID and optionally its ID type. This query relies on the ProductContentFull fragment for comprehensive product data. ```graphql query GetProduct($id: ID!, $idType: ProductIdTypeEnum) { product(id: $id, idType: $idType) { ...ProductContentFull } } ``` -------------------------------- ### Execute GraphQL Query and Get Response in PHP Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This PHP code shows how to execute a GraphQL query using the `$this->graphql()` utility function, which is a wrapper for WPGraphQL's `graphql()` function. It takes an array of request data, including the query, and returns the response as an associative array, making it suitable for testing. ```php $response = $this->graphql( [ 'query' => $query ] ); ``` -------------------------------- ### Complete Test Case for Item Count Field in PHP Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This PHP code presents a complete test class `ItemCountTest` that extends `WooGraphQLTestCase`. It includes the setup of the test scenario, definition of the GraphQL query, execution of the query, and assertion of the response for the `itemCount` field, demonstrating a full test cycle. ```php $this->factory->product->createSimple(), 'quantity' => 1, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 1, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 2, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 3, ], ]; $this->factory->cart->add( ...$products ); $query = ' query { cart { contents { nodes { quantity } } itemCount } } '; $response = $this->graphql( [ 'query' => $query ] ); $expected = [ $this->expectedField( 'cart.itemCount', array_sum( array_column( $products, 'quantity' ) ) ), ]; $this->assertQuerySuccessful( $response, $expected ); } } ``` -------------------------------- ### WordPress wp_hash() Function in JavaScript using crypto-js Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/harmonizing-with-wordpress.md Adapts the WordPress `wp_hash` function to JavaScript, utilizing the `crypto-js` library for HMAC-MD5 hashing. It requires `NONCE_KEY` and `NONCE_SALT` environment variables to be set. Install `crypto-js` using `npm install crypto-js`. ```javascript import { HmacMD5 } from 'crypto-js'; export function wpNonceHash(data) { const nonceSalt = process.env.NONCE_KEY + process.env.NONCE_SALT; const hash = HmacMD5(data, nonceSalt).toString(); return hash; } ``` -------------------------------- ### Generate Transfer Session URL in JavaScript Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/harmonizing-with-wordpress.md Generates a secure URL for session transfer using client-side nonces. It decodes a session token with `jwt-decode` (install with `npm install jwt-decode`), determines the nonce action and parameter, creates the nonce, and constructs the final URL, including a placeholder for subscription IDs if applicable. Requires `WORDPRESS_URL` environment variable. ```javascript import jwtDecode from 'jwt-decode'; function getAction(action, uId) { switch (action) { case 'cart': return `load-cart_${uId}`; case 'checkout': return `load-checkout_${uId}`; case 'new-payment': return `load-account_${uId}`; case 'change-sub': return `change-sub_${uId}`; case 'renew-sub': return `renew-sub_${uId}`; default: throw new Error('Invalid nonce action provided.'); } } function getNonceParam(action) { switch (action) { case 'cart': return '_wc_cart'; case 'checkout': return '_wc_checkout'; case 'new-payment': return '_wc_payment'; case 'change-sub': return '_wc_change_sub'; case 'renew-sub': return '_wc_renew_sub'; default: throw new Error('Invalid nonce action provided.'); } } export function generateUrl(sessionToken, clientSessionId, actionType) { const decodedToken = jwtDecode(sessionToken); if (!decodedToken?.data?.customer_id) { throw new Error('Failed to decode session token'); } const uId = decodedToken.data.customer_id; const action = getAction(actionType, uId); // Create nonce const nonce = createNonce(action, uId, clientSessionId); // Create URL. const param = getNonceParam(actionType); let url = `${process.env.WORDPRESS_URL}/transfer-session?session_id=${uId}&${param}=${nonce}`; // Add subscription ID placeholder if subscription action. if (actionType === 'change-sub' || actionType === 'renew-sub') { url = `${url}&sub=%SUBSCRIPTION_ID%`; } return url; } ``` -------------------------------- ### Display Subscription Product Details in React Component Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-subscription-data-and-mutations.md This React component example demonstrates how to display basic subscription product information within a product listing. It shows placeholders for product name, price, and subscription period. The `product` prop is expected to contain subscription details, and an `addToCart` function is assumed to handle adding the product to the cart. ```javascript function ProductListing({ product }) { // ... other code return (

{product.name}

Price: {product.price}

Subscription Price: {product.subscriptionPrice}

Subscription Period: {product.subscriptionPeriod}

// ... other product details
); }; ``` -------------------------------- ### GraphQL Query to Get a Single Product Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-cart-data.md Fetches detailed information for a specific product using its ID and optional ID type. This query utilizes the `ProductContentFull` fragment for comprehensive product data retrieval. It's essential for displaying individual product details on a storefront. ```javascript export const GetProduct = gql` query GetProduct($id: ID!, $idType: ProductIdTypeEnum) { product(id: $id, idType: $idType) { ...ProductContentFull } } `; ``` -------------------------------- ### Get Session Token from Local Storage or Fetch Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/configuring-graphql-client-for-user-session.md Retrieves a session token from localStorage. If not found or if `forceFetch` is true, it fetches a new token using `fetchSessionToken`. This function is crucial for maintaining user sessions in the application. ```javascript export async function getSessionToken(forceFetch = false) { let sessionToken = localStorage.getItem(process.env.SESSION_TOKEN_LS_KEY as string); if (!sessionToken || forceFetch) { sessionToken = await fetchSessionToken(); } return sessionToken; } ``` -------------------------------- ### React: BundleProduct Component Setup for WooGraphQL Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-product-bundle-data-and-mutations.md This React component, `BundleCard`, is designed to display product bundle information within a WooGraphQL-integrated application. It imports necessary hooks and components for cart mutations and session management, serving as a base for handling product bundle data. ```jsx import React, { useState } from 'react'; import useCartMutations from './useCartMutations'; import { useSession } from './SessionProvider'; import { LoadingSpinner } from './LoadingSpinner'; import { CartCard } from './CartCard'; // ... rest of the code from the provided sample ... export function BundleCard({ product }) { // ... rest of the code from the provided sample ... } ``` -------------------------------- ### Get Product Variation Details GraphQL Query Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-session-and-using-cart-mutations.md Fetches details for a specific product variation using its ID. This query uses the VariationContent fragment to get all relevant variation attributes. ```graphql query GetProductVariation($id: ID!) { productVariation(id: $id, idType: DATABASE_ID) { ...VariationContent } } ``` -------------------------------- ### Create Test Scenario with Products and Cart in PHP Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This PHP code demonstrates how to set up a test scenario by creating multiple products with specified quantities and adding them to a cart using factory helper functions. It utilizes `$this->factory->product->createSimple()` to generate products and `$this->factory->cart->add()` to populate the cart. ```php public function testMe() { // Our scenario $products = [ [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 1, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 1, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 2, ], [ 'product_id' => $this->factory->product->createSimple(), 'quantity' => 3, ], ]; $this->factory->cart->add( ...$products ); } ``` -------------------------------- ### Configure Codeception for Testing (Bash) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This sequence of commands copies the default Codeception configuration file and prompts for necessary modifications within codeception.yml. These steps are essential for setting up Codeception to run tests within the project's environment. ```bash cp codeception.dist.yml codeception.yml # Modify codeception.yml as per instructions ``` -------------------------------- ### Get Cart and Customer Information GraphQL Query Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-session-and-using-cart-mutations.md Retrieves the current shopping cart contents and customer information, if a customer ID is provided. It utilizes CartContent and CustomerContent fragments. ```graphql query GetCart($customerId: Int) { cart { ...CartContent } customer(customerId: $customerId) { ...CustomerContent } } ``` -------------------------------- ### Run WPUnit Tests (Bash) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This command executes all WordPress unit tests using the Codeception framework. It assumes that the testing environment and Codeception have been correctly configured in previous steps. Successful execution should result in all tests passing. ```bash vendor/bin/codecept run wpunit ``` -------------------------------- ### Apollo Client Initialization with Session Management Links Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/configuring-graphql-client-for-user-session.md Illustrates how to create an Apollo Client instance with a customized 'link' option. It utilizes the 'from' utility function to chain multiple ApolloLink instances, including placeholders for session-related links ('createSessionLink', 'createErrorLink', 'createUpdateLink') before the HttpLink. ```javascript import { from } from '@apollo/client'; // ... const client = new ApolloClient({ link: from([ createSessionLink(), createErrorLink(), createUpdateLink(), new HttpLink({ uri: endpoint }), ]), cache: new InMemoryCache(), }); ``` -------------------------------- ### Environment Variables for WPGraphQL WooCommerce (.env file) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/configuring-graphql-client-for-user-session.md Sample `.env` file content for configuring WPGraphQL WooCommerce. These variables are loaded using the `dotenv` package and store sensitive information like session tokens keys, authentication timeouts, and the GraphQL endpoint URL. ```makefile SESSION_TOKEN_LS_KEY=my_session_token REFRESH_TOKEN_LS_KEY=my_refresh_token AUTH_TOKEN_LS_KEY=my_auth_token AUTH_KEY_TIMEOUT=30000 GRAPHQL_ENDPOINT=http://woographql.local/graphql ``` -------------------------------- ### Update NodeByUri GraphQL Query for Pagination Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md Modifies the `NodeByUri` GraphQL query to include `first` and `after` variables for pagination. This allows fetching a specific number of products and controlling the data's starting point by querying `contentNodes` within the `nodeByUri` field. ```graphql query NodeByUri($uri: ID!, $first: Int, $after: String) { nodeByUri(uri: $uri) { ... on Product { id name shortDescription price image { sourceUrl altText } } contentNodes(first: $first, after: $after) { edges { cursor node { ... on Product { id name shortDescription ... on SimpleProduct { price } ... on VariableProduct { price } image { sourceUrl altText } } } } pageInfo { hasNextPage endCursor } } } } ``` -------------------------------- ### Generate WPUnit Test File with Codeception Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md Generates a new WPUnit test file using the Codeception CLI. This command is part of the wp-browser package, which manages Codeception dependencies for WPGraphQL testing. ```bash vendor/bin/codecept generate:wpunit wpunit "ItemCount" ``` -------------------------------- ### Generate Next.js App with create-woonext-app CLI Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/README.md The `create-woonext-app` CLI tool generates a pre-configured Next.js e-commerce application. It is designed to streamline the development process for integrating WooCommerce and its extensions with React applications. The generated app utilizes the `@woographql` packages. ```bash npx create-woonext-app [options] ``` -------------------------------- ### Running WP Unit Tests with Codeception in Debug Mode Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This bash command executes a specific Codeception test suite for WordPress unit tests. It targets the 'ItemCountTest' and enables the '--debug' flag, which provides detailed output during execution, useful for diagnosing query failures and understanding WPGraphQL responses. ```bash vendor/bin/codecept run wpunit ItemCountTest --debug ``` -------------------------------- ### GraphQL Query to Get a Product Variation Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-cart-data.md Retrieves details for a specific product variation using its database ID. This query employs the `VariationContent` fragment for focused variation data. It's useful for fetching specific attributes and pricing of a product variation. ```javascript export const GetProductVariation = gql` query GetProductVariation($id: ID!) { productVariation(id: $id, idType: DATABASE_ID) { ...VariationContent } } `; ``` -------------------------------- ### Implement ShopPage Component with FetchMore for Pagination Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md A React component that uses Apollo Client's `useQuery` hook to display products and implement a 'Load More' functionality. It manages pagination state, fetches initial products with a `first` variable, and uses `fetchMore` to load subsequent product batches based on `endCursor`. ```jsx import React from 'react'; import { useQuery } from '@apollo/client'; import ProductListing from './ProductListing'; // Import the NodeByUri query here import { NodeByUri } from './graphql'; const ShopPage = () => { const { loading, error, data, fetchMore } = useQuery(NodeByUri, { variables: { uri: '/shop', first: 10 }, }); const loadMoreProducts = () => { if (data.nodeByUri.contentNodes.pageInfo.hasNextPage) { fetchMore({ variables: { after: data.nodeByUri.contentNodes.pageInfo.endCursor, }, }); } }; if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const products = data?.nodeByUri?.contentNodes?.edges?.map( ({ node }) => node ) || []; return ( <> ); }; export default ShopPage; ``` -------------------------------- ### GraphQL Query to Get Cart and Customer Data Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-cart-data.md Fetches the current user's cart contents and customer information, including session tokens and shipping details. This query uses `CartContent` and `CustomerContent` fragments. It's vital for displaying cart summaries and user-specific data. ```javascript export const GetCart = gql` query GetCart($customerId: Int) { cart { ...CartContent } customer(customerId: $customerId) { ...CustomerContent } } `; ``` -------------------------------- ### Define GraphQL Fragments and Queries for Product Data Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-product-data.md Defines GraphQL fragments and queries for fetching full product content and specific product details using WPGraphQL. This includes product ID, name, description, pricing, images, attributes, and variations. It's used with Apollo Client to interact with the WooCommerce backend. ```javascript import { gql } from '@apollo/client'; export const ProductContentFull = gql` fragment ProductContentFull on Product { id databaseId slug name type description shortDescription(format: RAW) image { id sourceUrl altText } galleryImages { nodes { id sourceUrl(size: WOOCOMMERCE_THUMBNAIL) altText } } productTags(first: 20) { nodes { id slug name } } attributes { nodes { id attributeId ... on LocalProductAttribute { name options variation } ... on GlobalProductAttribute { name options variation } } } ... on SimpleProduct { onSale stockStatus price rawPrice: price(format: RAW) regularPrice salePrice stockStatus stockQuantity soldIndividually } ... on VariableProduct { onSale price rawPrice: price(format: RAW) regularPrice salePrice stockStatus stockQuantity soldIndividually variations(first: 50) { nodes { id databaseId name price rawPrice: price(format: RAW) regularPrice salePrice onSale attributes { nodes { name label value } } } } } } `; export const GetProduct = gql` query GetProduct($id: ID!, $idType: ProductIdTypeEnum) { product(id: $id, idType: $idType) { ...ProductContentFull } } `; ``` -------------------------------- ### ProductListing Component for Display Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md A React component responsible for rendering a list of products. It receives an array of product objects as props and maps over them to display each product's name, short description, price, and image. This component focuses solely on the presentation of product data, abstracting away the data fetching logic. ```jsx import React from 'react'; const ProductListing = ({ products }) => { return (

Shop

    {products.map((product) => (
  • {product.name}

    {product.shortDescription}

    Price: {product.price}

    {product.image.altText}
  • ))}
); }; export default ProductListing; ``` -------------------------------- ### Extend WooGraphQLTestCase for Unit Tests (PHP) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This snippet demonstrates extending the `WooGraphQLTestCase` class to create a custom unit test class in PHP. It leverages the WPGraphQLTestCase library for testing WPGraphQL responses. The test class `ItemCountTest` extends `WooGraphQLTestCase` and includes a basic test method `testMe`. ```php { const { data, loading, error } = useQuery(GetProduct, { variables: { id: productId, idType: 'DATABASE_ID' }, }); if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const product = data.product; return (
{/* Render product information here */}
); }; export default SingleProduct; ``` -------------------------------- ### Render Fetched Product Information in React Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-product-data.md Renders detailed product information within a React component. It displays the product name, description (using dangerouslySetInnerHTML), price (including sale price), and attributes. This code snippet is intended to be part of the `SingleProduct` component. ```javascript // Inside the SingleProduct component, after defining the `product` constant return (

{product.name}

{product.onSale && {product.regularPrice}} {product.price}

{product.attributes.nodes.map((attr) => (
{attr.name}: {attr.options.join(', ')}
))}
{/* Add the width, height, length, and weight information */} {/* Add the cart options section */}
); ``` -------------------------------- ### ShopPage Component with useQuery Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md A React component that utilizes the `useQuery` hook from `@apollo/client` to fetch data using the `NodeByUri` GraphQL query. It passes a specific URI ('/shop') as a variable to the query. The component handles loading and error states and then processes the fetched data to extract a list of products, which are then passed to the `ProductListing` component for rendering. ```jsx import React from 'react'; import { useQuery } from '@apollo/client'; import ProductListing from './ProductListing'; // Import the NodeByUri query here import { NodeByUri } from './graphql'; const ShopPage = () => { const { loading, error, data } = useQuery(NodeByUri, { variables: { uri: '/shop' }, }); if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const products = data?.nodeByUri?.contentNodes?.edges?.map( ({ node }) => node ) || []; return ; }; export default ShopPage; ``` -------------------------------- ### GraphQL Login Mutation (JavaScript) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-authentication.md Defines a GraphQL mutation for logging in a user. It accepts username and password and returns authentication tokens, refresh tokens, and customer session information. Requires the gql function from @apollo/client. ```javascript import { gql } from '@apollo/client'; const LoginDocument = gql` mutation Login($username: String!, $password: String!) { login(input: { username: $username, password: $password }) { authToken refreshToken customer { sessionToken } } } `; ``` -------------------------------- ### Implement Login Callback Function (JavaScript) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/handling-user-authentication.md Handles the user login process by making a GraphQL request to the login mutation. It sets the 'woocommerce-session' header if a session token exists, retrieves new credentials, and saves them. Requires rawRequest from graphql-request, GraphQLClient, LoginDocument, getSessionToken, and saveCredentials. ```javascript import { rawRequest } from 'graphql-request'; export async function login(username, password) { const headers = {}; const sessionToken = await getSessionToken(); if (sessionToken) { headers['woocommerce-session'] = `Session ${sessionToken}`; } try { const graphQLClient = new GraphQLClient(process.env.SHOP_GRAPHQL_ENDPOINT, { headers }); const { data, headers: responseHeaders, status, } = await rawRequest( process.env.GRAPHQL_ENDPOINT as string, LoginDocument, { username, password }, headers, ); const loginResults = data?.login; const newSessionToken = responseHeaders.get('woocommerce-session'); const { authToken, refreshToken, customer, } = loginResults; if (!authToken || !refreshToken || !newSessionToken) { throw new Error( 'Failed to retrieve credentials.'); } } catch (error) { throw new Error(error); } saveCredentials(authToken, newSessionToken, refreshToken); return customer; } ``` -------------------------------- ### Display Product Dimensions and Weight in React Component Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-product-data.md This React JSX code demonstrates how to render the product's dimensions and weight information fetched via GraphQL. It assumes that the `product` object contains `dimensions` (with width, height, length) and `weight` properties, displaying them in a structured format within the Single Product component. ```jsx
Dimensions: {product.dimensions.width} x {product.dimensions.height} x {product.dimensions.length}
Weight: {product.weight}
``` -------------------------------- ### PHP Test for Cart Item Count in WPGraphQL Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/local-testing.md This PHP code snippet defines a test case for WPGraphQL's cart functionality. It creates a simple product, adds it to the cart, and then queries the cart to check the 'itemCount'. The test is designed to initially fail to demonstrate the need for implementing the 'itemCount' field. ```php $this->factory->product->createSimple(), 'quantity' => 3, ], ]; $this->factory->cart->add( ...$products ); $query = ' query { cart { contents { nodes { quantity } } itemCount } } '; $response = $this->graphql( [ 'query' => $query ] ); $expected = [ $this->expectedField( 'cart.itemCount', array_sum( array_column( $products, 'quantity' ) ) ), ]; $this->assertQuerySuccessful( $response, $expected ); } } ``` -------------------------------- ### Implement Sorting in ShopPage Component Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md This React component demonstrates how to integrate sorting into a shop page using Apollo Client. It includes a state variable for sorting, updates the `useQuery` hook with sorting variables, and provides a dropdown to change the sort order. It also includes functionality for fetching more products. ```javascript import React from 'react'; import { useQuery } from '@apollo/client'; import ProductListing from './ProductListing'; // Import the NodeByUri query here import { NodeByUri } from './graphql'; const ShopPage = () => { const [sort, setSort] = useState(null); const { loading, error, data, fetchMore } = useQuery(NodeByUri, { variables: { uri: '/shop', first: 10, where: sort }, }); const loadMoreProducts = () => { if (data.nodeByUri.contentNodes.pageInfo.hasNextPage) { fetchMore({ variables: { after: data.nodeByUri.contentNodes.pageInfo.endCursor, }, }); } }; const handleSortChange = (e) => { setSort({ orderby: e.target.value }); }; if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const products = data?.nodeByUri?.contentNodes?.edges?.map( ({ node }) => node ) || []; return ( <> ); }; export default ShopPage; ``` -------------------------------- ### React Component for Product Filtering and Sorting (ShopPage) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/routing-by-uri.md This React component utilizes Apollo Client's useQuery hook to fetch and display products. It includes state management for search terms and sorting preferences, and integrates a search input and select dropdown for user interaction. It's designed to work with the NodeByUri GraphQL query. ```jsx import React from 'react'; import { useQuery } from '@apollo/client'; import ProductListing from './ProductListing'; // Import the NodeByUri query here import { NodeByUri } from './graphql'; const ShopPage = () => { const [sort, setSort] = useState(null); const [search, setSearch] = useState(''); const { loading, error, data, fetchMore } = useQuery(NodeByUri, { variables: { uri: '/shop', first: 10, where: { ...sort, search } }, }); const loadMoreProducts = () => { if (data.nodeByUri.contentNodes.pageInfo.hasNextPage) { fetchMore({ variables: { after: data.nodeByUri.contentNodes.pageInfo.endCursor, }, }); } }; const handleSortChange = (e) => { setSort({ orderby: e.target.value }); }; const handleSearchChange = (e) => { setSearch(e.target.value); }; if (loading) return

Loading...

; if (error) return

Error: {error.message}

; const products = data?.nodeByUri?.contentNodes?.edges?.map( ({ node }) => node ) || []; return ( <> ); }; export default ShopPage; ``` -------------------------------- ### Import Core Hooks for Cart Page Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-cart-data.md Imports essential React hooks and custom hooks for managing session and cart mutations. These are foundational for building the cart functionality. ```javascript import React, { useState } from 'react'; import { useSession } from './SessionProvider'; import { useCartMutations, useOtherCartMutations } from './useCartMutations'; import { ShippingInfo } from './ShippingInfo'; import { ApplyCouponForm } from './ApplyCouponForm'; ``` -------------------------------- ### Prepare Secure Session Data for Update Session Mutation (JavaScript) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/harmonizing-with-wordpress.md This JavaScript code prepares the input object for the `updateSession` GraphQL mutation. It includes setting a secure, hashed client session ID and its expiration time. The expiration is calculated in seconds from the current time, ensuring the session data remains valid for a defined period. ```javascript const input = { sessionData: [ { key: 'client_session_id', value: 'secure_hashed_value', // Replace this with your secure hashed value. }, { key: 'client_session_id_expiration', value: `${Math.floor(new Date().getTime() / 1000) + 3600}`, }, ] } ``` -------------------------------- ### Create Apollo Client Session Link (JavaScript) Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/configuring-graphql-client-for-user-session.md Defines the `createSessionLink` function using Apollo Client's `setContext` to attach WooCommerce session tokens to outgoing GraphQL requests. It retrieves a session token and adds it to the request headers if available. This link is stateless and acts as middleware. ```javascript import { setContext } from '@apollo/client/link/context'; function createSessionLink() { return setContext(async (operation) => { const headers = {}; const sessionToken = await getSessionToken(); if (sessionToken) { headers['woocommerce-session'] = `Session ${sessionToken}`; return { headers }; } return {}; }); } ``` ```javascript import { ApolloLink } from '@apollo/client'; const consoleLink = new ApolloLink((operation, forward) => { operation.setContext(/* our callback */); return forward(operation); }); ``` -------------------------------- ### Login Page Component with `login` Mutation in React.js Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-customer-data-and-mutations.md This React component demonstrates how to implement a login form that utilizes a `login` mutation. It captures user credentials, triggers the login mutation via a `SessionProvider`, and redirects the user upon successful authentication. Error handling for the login process is also included. ```jsx import React, { useState, useEffect } from 'react'; import { useSession } from './SessionProvider'; function LoginPage() { const [username, setUserName] = useState(''); const [password, setPassword] = useState(''); const { login, customer } = useSession(); const handleLogin = (event) => { event.preventDefault(); login(username, password); } useEffect(() => { if (customer?.id && customer.id !== 'guest') { // Redirect to account page. window.location.href = `${process.env.APP_URL}/account`; } }, [customer]) return (
setEmail(e.target.value)} placeholder="Enter Username or Email" required /> setPassword(e.target.value)} placeholder="Enter Password" required /> {error &&

Error: {error.message}

}
); } export default LoginPage; ``` -------------------------------- ### React Account Details Form using WPGraphQL Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-customer-data-and-mutations.md This React component creates a form for users to update their account details such as first name, last name, display name, email, and password. It utilizes the `useSession` hook to fetch customer data and execute the `updateCustomer` mutation upon form submission. The component includes basic state management for form inputs and password confirmation, with a note that error handling is intentionally minimal for illustrative purposes. ```jsx import React, { useState, useEffect } from 'react'; import { useSession } from './SessionProvider'; function AccountDetailsPage() { const [details, setDetails] = useState({}); const [confirmPassword, setConfirmPassword] = useState(''); const { customer, updateCustomer, fetching } = useSession(); useEffect(() => { if (fetching) { return; } if (!customer?.id || customer.id === 'guest') { // redirect to login window.location.href = `${process.env.APP_URL}/login`; } }); useEffect(() => { setDetails({ ...customer }) }, [customer]) const handleChange = (event) => { setDetails({ ...details, [event.target.name]: event.target.value }); }; const handleSubmit = async (event) => { event.preventDefault(); if (!!details.password && details.password !== confirmPassword) { alert('Passwords do not match'); return; } updateCustomer({ ...details }); }; if (!customer) { return null; } return (
{/* Repeat for other fields */} setConfirmPassword(event.target.value)} placeholder="Confirm Password" />
); } export default AccountDetailsPage ; ``` -------------------------------- ### Query Subscription Product Data with GraphQL Source: https://github.com/wp-graphql/wp-graphql-woocommerce/blob/develop/docs/using-subscription-data-and-mutations.md This GraphQL query retrieves detailed information for a subscription product, including its ID, name, price, and specific subscription parameters like period, interval, length, and sign-up fee. Ensure the `SubscriptionProduct` type is available in your WooGraphQL schema. ```javascript const SUBSCRIPTION_PRODUCT_QUERY = gql` query SubscriptionProduct($id: ID!) { product(id: $id) { ... on SubscriptionProduct { id name price subscriptionPrice subscriptionPeriod subscriptionPeriodInterval subscriptionLength subscriptionSignUpee } } } `; ```