When attempting to call a mutation on the client side in Next.js, I encounter an error every time I use the useMutation hook or the client itself, resulting in the following error: Cannot read property 'data' of undefined. See the code snippets below:
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
// More fields here...
}
}
`
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 and Components import...
// Component
export default function CartTemplate() {
// Hooks and state initialization...
// Function to submit order
const submitOrder = async (orders, numberOfOrders) => {
if (numberOfOrders > 0) {
try {
const r = await newOrderItem({
variables: {
id: orders[0].products[0].id,
amount: orders[0].products[0].amount
}
})
console.log('after', r)
} catch (err) {
console.log('error', err)
toast.error('...')
}
} else {
toast.warning('...')
}
}
// JSX return...
}
It is important to note that each time the function awaits the API response, it returns undefined.