【问题标题】:APOLLO CLIENT - Mutation not working (Cannot read property 'data' of undefined)APOLLO CLIENT - 突变不起作用(无法读取未定义的属性“数据”)
【发布时间】:2021-07-21 04:13:52
【问题描述】:

我试图在客户端(Nextjs)调用突变,但每次我使用 useMutation 钩子甚至客户端本身调用时,它都会返回以下错误:无法读取未定义的属性“数据”。代码:

Graphql 客户端

// 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 突变

// 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
          }
        }
      }
    }
  }
`

反应组件

// 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>
    </>
  )
}

请注意,每次函数等待 api 答案时,它都会返回 undefined。

【问题讨论】:

  • 错误在哪里?从回应?网络请求包含正确传递的变量?使用变量进行查询/突变测试的游乐场?传递整个(准备好的对象)“数据”变量,从 API 文档中读取输入类型类型
  • API 调用没有返回错误 :(。但我能够找到问题的根源。我在这个问题上添加了答案。

标签: javascript api graphql next.js apollo-client


【解决方案1】:

我找到了解决方案,它没有返回错误,因为它是 NextJs 错误。 Next js 在运行时返回 undefined on env variables,要解决这个问题,只需在 next.config.js 文件中配置公共运行时

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 2019-05-12
    • 2020-10-03
    • 2021-07-20
    • 1970-01-01
    • 2020-03-07
    • 2021-11-08
    • 2020-08-13
    • 2021-06-21
    相关资源
    最近更新 更多