Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get Cart query always return blank result #333

Closed
kenchoong opened this issue Aug 18, 2020 · 8 comments
Closed

Get Cart query always return blank result #333

kenchoong opened this issue Aug 18, 2020 · 8 comments
Labels
failing mutation Issue concerns a failing/broken mutation question Further information is requested

Comments

@kenchoong
Copy link

kenchoong commented Aug 18, 2020

I have a mutation to Add to cart like this:

import { gql } from '@apollo/client';

const ADD_TO_CART = gql`
  mutation ($input: AddToCartInput!) {
    addToCart(input: $input) {
      cartItem {
        key
        product {
          id
         ... some other field here
        }
        variation {
          id
          variationId
          name
         ... some other field here
        }
        quantity
        total
        subtotal
        subtotalTax
      }
    }
  }
`;

export default ADD_TO_CART;

This is Get Cart query:

const GET_CART = gql`
  query GetCart {
    cart {
      contents {
        nodes {
          key
          product {
            id
            productId
            name
            description
            
            .. some other field here
          }
          variation {
            id
            variationId
            name
            description
            .. some other field here
          } 
          quantity
          total
          subtotal
          subtotalTax
        }
      }
    
      subtotal
      subtotalTax
     
      .. some other field here
    }
  }
`;

export default GET_CART;

Then I call this mutation like this:

// here define the addToCartInput!
const addToCartInput = {
        clientMutationId: v4(),
        productId: productId,
        quantity: 1,
        variationId: product.variationId
    }

// Call to GET_CART query above 
const { loading, error, data, refetch } = useQuery(GET_CART, {
		notifyOnNetworkStatusChange: true,
		onCompleted: () => {
			
                console.log(data) // <-- this always return the blank cart

		}
	});

// Call to ADD_TO_CART mutation above 
const [addToCart,
        { loading: addToCartLoading, error: addToCartError, data: addToCartData }]
        = useMutation(ADD_TO_CART, {
            variables: {
                input: addToCartInput,
            },
            onCompleted: () => {
              
                console.log("completed add to cart")
                refetch(); // Refetch the query again for Updated cart by calling the GET_CART query above again 
            
            },
            onError: (error) => {
                // present the error 
                console.log(error)
            }
        });

As you can see above, I refetch() the GET_CART query when the onCompleted() of the addToCart mutation.

What I expect:
Therefore what I expect should be, initial it will be a blank cart(subtotal 0.00) , then when successful mutation, it will have the product inside it.

End Result:
But end up, everytime the GET_CART query will return the blank cart even the addToCart mutation is successful.

But weird thing is, when I using GraphiQL in wp-admin dashboard, it works as expected in What I expect section . If I having the successful mutation in GraphiQL, I get the data in cart using the GET_CART query.

So what I missing out? Cause I can't find any documentation on this. Cause when I checked the docs about the cart, I found this, https://woographql.com/guides/create-react-app/3-creating-the-cart which I didnt see any documentation.

Any help will be appreciated.

@kidunot89

@kenchoong kenchoong reopened this Aug 18, 2020
@kidunot89
Copy link
Member

@kenchoong Sounds like your missing the WooCommerce Session JWT. It allows WooCommerce keeps track of the session. See this React/Apollo example for more info on implementation.

Sorry, about the lack of documentation. I'm actually working on it, but it's slow going.

@kenchoong
Copy link
Author

@kidunot89 thanks a lot for your help.. You doing great plugin.

As state in the example provided, so means that I need to add middleware and afterware into the ApolloClient object right? Then the GET_CART query will work?

@kidunot89
Copy link
Member

kidunot89 commented Aug 18, 2020

Yes, it works like an HTTP Authorization token when using a plugin like WPGraphQL-JWT-Authentication.

The Apollo middleware will pass the WooCommerce session token if it's found in localStorage or whatever storage method you prefer and it will be passed as an HTTP request header on every request.

The afterware will retrieve and overwrite the token with any new token it may receive in a woocommerce-session HTTP response header. This will only happen on addToCart currently.

That's if your middleware and afterward are configured like in the example.

When the request is being processed by the server, WooGraphQL retrieves and decodes the token, then passing the session user ID to WooCommerce and the session data is identified in the data and loaded. If the token is updated it will send the updated token in a HTTP response header, when the mutation is processed. Small note: Currently only addToCart is the only mutation that will create a new session token currently. Customer and User mutations will not.

WooCommerce Session data includes any customer data for users not registered and cart data.

Session data is periodically deleted with WP-Cron if I'm not mistaken.

Also if you wish to login and/or register customers from/to the WordPress database, you have to use a plugin for user authentication like WPGraphQL-JWT-Authentication as well as the WooCommerce sessions.

@kidunot89 kidunot89 added failing mutation Issue concerns a failing/broken mutation question Further information is requested labels Aug 18, 2020
@kenchoong
Copy link
Author

Wow.. thanks a lot.. Now I have the basic concept, let me try this later.. Thank you very much

@kenchoong
Copy link
Author

It works after implement the Middleware and Afterware into ApolloClient.. Thank you very much!!

@Manorama-Singh
Copy link

@kidunot89 I providing JWT token but session not work for AddToCart, getCart and CustomerQuery......Please help me.

@AmirAmArA
Copy link

is someone still follwoing here? @kidunot89
i have the same problem , I even tried it using the playground on Wordpress still returns blank

@kidunot89
Copy link
Member

@AmirAmArA have you read the docs on configuring the client and updated to the latest version of all WPGraphQL/WooGraphQL plugins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
failing mutation Issue concerns a failing/broken mutation question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants