Gabriel Mazurco
Gabriel Mazurco

Reputation: 43

APOLLO CLIENT - Mutation not working (Cannot read property 'data' of undefined)

I m trying to call a mutation on client side (Nextjs), but every time i call using the useMutation hook or even the client itself it returns the following error: Cannot read property 'data' of undefined. Code:

Graphql Client

// Dependencies
import { ApolloClient, InMemoryCache } from '@apollo/client'

// GraphQL Host location
/* eslint-disable-next-line */
const endpoint = process.env.GRAPHQL_HOST

// Graphql client instance
export const graphqlClient = new ApolloClient({
  uri: endpoint,
  cache: new InMemoryCache(),
  headers: {
    /* eslint-disable-next-line */
    authorization: `Bearer ${process.env.GRAPHQL_TOKEN}`
  }
})

Graphql mutation

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

// Mutations
export const CREATE_ORDER_ITEM = gql`
  mutation newOrderItem($id: ID!, $amount: Int!) {
    createOrderItem(data: {product: {connect: {id: $id}}, amount: $amount}) {
      id
      amount
      product {
        id
        description
        slug
        unitPrice
        ncm
        publishStatus
        images {
          url
          height
          width
        }
        category {
          id,
          name
        }
        customer {
          id
          name
          slug
          cnpj
          email
          cep
          city
          logo {
            height
            width
            url
          }  
          location {
            latitude
            longitude
          }
        }
        variants {
          __typename
          ...on ProductSizeVariant {
            id
            name
            size
          }
          ...on ProductColorVariant {
            id
            name
            color {
              hex
            }
          }
          ...on ProductHeightVariant {
            id
            name
            height
          }
          ...on ProductUnitVariant {
            id
            name
            unit
          }
        }
      }
    }
  }
`

React Component

// Dependencies
import { CREATE_ORDER_ITEM } from 'api/mutations'
import { useMutation } from '@apollo/client'
import { toast } from 'react-toastify'
import { useShoppingCart } from 'hooks'

// Styles
import * as S from './styles'

// Components
import { Container, Column, CustomModal } from 'styles/global'
import { CartSubtotal, CartTable, LoadingModalBody } from 'components'

// Component
export default function CartTemplate() {

  // Hooks
  const { state: items } = useShoppingCart()
  const [ newOrderItem ] = useMutation(CREATE_ORDER_ITEM)

  // Actions
  const submitOrder = async (orders, numberOfOrders) => {
    if (numberOfOrders > 0) {

      try {

        // Sample api call
        const r = await newOrderItem({
          variables: {
            id: orders[0].products[0].id,
            amount: orders[0].products[0].amount
          }
        })

        // ALWAYS IS RETURNING UNDEFINED
        console.log('after', r)

      } catch (err) {
        console.log('error', err)
        toast.error('...')
      }
      
    } else {
      toast.warning('...')
    }
  }

  // JSX
  return (
    <>
      <S.Wrapper>
        <Container ph="0">
          <Column ph="0" sm={12} md={12} lg={9}>
            <CartTable items={items} />
          </Column>
          <Column ph="0" sm={12} md={12} lg={3}>
            <CartSubtotal
              items={items}
              onSubmitOrder={submitOrder}
            />
          </Column>
        </Container>
      </S.Wrapper>
      <CustomModal isOpen={false}>
        <LoadingModalBody />
      </CustomModal>
    </>
  )
}

Note that everytime the function awaits the api answer it returns undefined.

Upvotes: 0

Views: 1810

Answers (1)

Gabriel Mazurco
Gabriel Mazurco

Reputation: 43

I found the solution, it was returning no error cause it was NextJs fault. Next js returns undefined on env variables in runtime, to solve this issue just config public runtime in the next.config.js file

Upvotes: 2

Related Questions