11import React , { useState } from 'react' ;
22import { useMutation , useLazyQuery , gql } from '@apollo/client' ;
33
4- // Function to generate the cart create mutation
5- const getCartCreateMutation = ( firstName , surname , phone ) => gql `
6- mutation {
7- cartCreate(input: { attributes: { firstName: "${ firstName } ", surname: "${ surname } ", phone: "${ phone } " } }) {
4+ const getCartCreateMutation = gql `
5+ mutation CreateCart($input: CartCreateInput!) {
6+ cartCreate(input: $input) {
87 cart {
98 id
109 firstName
@@ -15,10 +14,9 @@ const getCartCreateMutation = (firstName, surname, phone) => gql`
1514 }
1615` ;
1716
18- // Function to generate the cart query
19- const getCartQuery = ( id ) => gql `
20- query {
21- cart(id: "${ id } ") {
17+ const getCartQuery = gql `
18+ query GetCart($id: ID!) {
19+ cart(id: $id) {
2220 id
2321 firstName
2422 surname
@@ -38,21 +36,33 @@ const CartForm = () => {
3836 const [ fetchCartWarning , setFetchCartWarning ] = useState ( '' ) ;
3937
4038 // Set up the mutation and query hooks with error handling
41- const [ createCartMutation , { data : createdCartData , error : createCartError } ] = useMutation ( getCartCreateMutation ( firstName , surname , phone ) ) ;
42- const [ fetchCartQuery , { data : fetchedCart , error : fetchCartError } ] = useLazyQuery ( getCartQuery ( cartId ) ) ;
39+ const [ createCartMutation , { data : createdCartData , error : createCartError } ] = useMutation ( getCartCreateMutation ) ;
40+ const [ fetchCartQuery , { data : fetchedCart , error : fetchCartError } ] = useLazyQuery ( getCartQuery ) ;
4341
4442 // Handle the cart creation
4543 const handleCreateCart = ( e ) => {
4644 e . preventDefault ( ) ;
4745 setCreateCartWarning ( '' ) ; // Reset warning
48- createCartMutation ( ) ;
46+ createCartMutation ( {
47+ variables : {
48+ input : {
49+ attributes : {
50+ firstName,
51+ surname,
52+ phone
53+ }
54+ }
55+ }
56+ } ) ;
4957 } ;
5058
5159 // Handle the cart fetching
5260 const handleFetchCart = ( e ) => {
5361 e . preventDefault ( ) ;
5462 setFetchCartWarning ( '' ) ; // Reset warning
55- fetchCartQuery ( ) ;
63+ fetchCartQuery ( {
64+ variables : { id : cartId }
65+ } ) ;
5666 } ;
5767
5868 // Update the state with the results of the mutation
@@ -206,4 +216,4 @@ const CartForm = () => {
206216 ) ;
207217} ;
208218
209- export default CartForm ;
219+ export default CartForm ;
0 commit comments