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

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

Allow foreign characters with regex while excluding special symbols

While browsing, I came across this thread: Is there a regular expression to match non-English characters?. It provides a regex to remove foreign characters using the code snippet str = str.replace(/[^\x00-\x7F]+/g, "");. My goal is slightly diff ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

Is there a way to display the true colors of a picture thumbnail when we click on it?

In my project, I attempted to create a dynamic color change effect when clicking on one of four different pictures. The images are displayed as thumbnails, and upon clicking on a thumbnail, it becomes active with the corresponding logo color, similar to t ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Which is better for cycling through a list of items: CSS or JavaScript?

Currently, I have a navigation bar set up as an unordered list (<ul>), but some list items are not visible. I want to implement functionality where clicking arrows will move the elements left or right by hiding or showing the leftmost or rightmost it ...

A dynamic way to refresh select options in HTML with PHP and JavaScript powered by JQuery

Imagine a scenario with the following layout: There is a table called "Regions" with columns "id" and "name". Also, there is another table named "Cities" containing columns "id", "region_id", and "name". How can you efficiently refill an HTML select opt ...

The tag dimensions are not displaying correctly

I've successfully developed a reusable heading component for my Next.js application. While debugging, it correctly displays the tag name, but unfortunately, there is no visual difference in styling at any level of tags. import React from 'react&a ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Usage of Firebase data

Looking for assistance on how to retrieve data from Firebase Cloud Store. My code includes the Firebase configuration and app.js but I'm facing an issue where the page appears blank on localhost:3000 without any errors. Below is the firebase.js confi ...

After converting from php/json, JavaScript produces a singular outcome

After running a PHP query and converting the result to JSON using json_encode, I noticed that when I try to print the results using echo, only one entry from the query is output in JSON format. My objective is to make this information usable in JavaScript ...

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

Using AngularJS to filter options in a dropdown list and trigger a function with ng-change

I have a dropdown menu that is being formatted using filters to display the text in a certain way. I need to send the selected item's ID value to the controller instead of just the name: <select ng-model="my_field" ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

Fetching information using vercel and nextjs

Currently, I have set up a website hosted on Vercel. The challenge at hand is that I am trying to fetch data server-side and then render it client-side in a component. Upon reviewing the code, something just doesn't feel right. I usually use useEffe ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

What is the best way to modify JSON data within a file?

To start, I retrieve a JSON array by using the following JavaScript code: $.getJSON("myJSONfile.json") .done(function(data) { myData = data; }); After storing the data in myData, which is a global variable, I proceed to add more informati ...

The random string generator is selecting a unique string for both the server and client side

I am facing an issue with a component in Next.js (v14.2.1) where I need to display a random string while fetching data. Despite my attempts, I can't seem to maintain the same string on both server and client sides. Below is the code snippet I am curr ...