Issue with Apollo Client - Mutation failing due to undefined property 'data'

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.

Answer №1

After a thorough investigation, I was able to identify the solution to the problem at hand. It turns out that the absence of any error messages was due to a fault in NextJs. This is because Next.js has a tendency to return undefined values for environment variables during runtime. The recommended approach to resolving this issue is by configuring the public runtime in the next.config.js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. Here is the code snippet: <div class="col-md-5 col-xs-12"> <p-dropdown [op ...

What is the best way to host a Next.js App on Netlify?

I've encountered a problem with my Next.js app deployment. Following a tutorial from netlify's blog on implementing Server-side Rendering for Next.js using netlify, I managed to build the app successfully but it's not functioning as expected ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

Guide to selecting and clicking multiple elements with a specific class using jQuery

On my html page, I have the following elements: $(".pv-profile-section__card-action-bar").length 3 I want to click on all of these elements instead of just the first one. Currently, I am achieving this with the code: $(".pv-profile-section__card-action- ...

Retrieve nested items in an array using Mongoose API's _id parameter

I am currently creating an API using Express and Mongoose, with Backbone on the front end. In my Mongoose User model, there is an array called "orders" that stores order details. My goal is to implement a create method that will retrieve a Single Order by ...

Designing personalized buttons on React Google Maps

Currently tackling a personal project that involves react-google-maps, but I'm struggling to display custom buttons on the map. My goal is to create a menu button that hovers over the map, similar to the search bar in the top left corner of Google Map ...

Create a new object by extracting JSON data using JavaScript

I am attempting to extract various data elements from a JSON file and place them into an object. My ultimate goal is to then convert this object back to JSON format, containing only the desired data. I believe that structuring the object like this might w ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Is there a way to raise an error in React Native and make it visible?

I am working on a functional component where I need to call a method from another .js file. The method in the external file intentionally throws an error for testing purposes, but I want to propagate this error up to the functional component's method. ...

A simple guide on passing a variable from Node.js to the view

Currently, I am delving into the world of Node.js and encountering a hurdle in sending a variable from app.js to index.html without relying on Jade or any other template engine. Below is my implementation in app.js: var express = require("express"); var ...

Are the commands overlapping?

Currently, I am in the process of developing a dynamic discord chat bot using JavaScript and node.js. One of my goals is to implement a specific command without interfering with an existing one. The bot functions flawlessly across all servers where it is ...

Start CSS3 Animation Automatically

I am working on a multi-page website with a slider that includes a CSS3 animation featuring the famous rocket animation. Here is the code snippet I used: #outerspace { position: relative; height: 400px; background: #fff; color: #fff; } di ...

Need help with writing code in Angular for setting intervals and clearing intervals?

I am working on the functionality to display a loader gif and data accordingly in Angular. I have tried using plain JavaScript setInterval code but it doesn't work for $scope.showLoader=true and $scope.showResult=true. The console.log('found the ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...

HTML5 Dragend event failed to trigger in Firefox

While working on my project, I encountered an issue where the 'dragend' event is not fired in Firefox 22.0 on Ubuntu but works perfectly fine in Chrome. I have written a logic to make changes on drag start and revert them if drop fails, triggered ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

Steps for integrating WebRTC recording functionality with a Node.js server

Looking to develop a user-friendly video blogging solution that utilizes WebRTC technology for direct recording of video/audio within the browser, similar to Youtube's My_Webcam. The backend should be powered by Node.js. While exploring various Node. ...

Exploring THREE.Points, navigating through JSON data, and looping through different materials

After exporting some JSON data from Blender using three.js' addon, I am trying to extract colors from the materials associated with the geometry and convert them to "point" material types. Even though my console logs display that my .forEach function ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...