How to resolve the issue of "Fixing 'Unhandled Runtime Error TypeError: event is undefined'"

Today I encountered this error:

Unhandled Runtime Error TypeError: event is undefined

and couldn't find a solution online

Here's the code snippet:

import { ethers } from 'ethers'
import { create as ipfsHttpClient } from 'ipfs-http-client'
import { useRouter } from 'next/router'
import Web3Modal from 'web3modal'

const client = ipfsHttpClient('https://ipfs.infura.io:5001/api/v0')

import {
  nftaddress, nftmarketaddress
} from '../config'

import NFT from '../artifacts/contracts/NFT.sol/NFT.json'
import Market from '../artifacts/contracts/Market.sol/NFTMarket.json'
export default function CreateItem() {
  const [fileUrl, setFileUrl] = useState(null)
  const [formInput, updateFormInput] = useState({ price: '', name: '', description: '' })
  const router = useRouter()

  async function onChange(e) {
    const file = e.target.files[0]
    try {
      const added = await client.add(
        file,
        {
          progress: (prog) => console.log(`received: ${prog}`)
        }
      )
      const url = `https://ipfs.infura.io/ipfs/${added.path}`
      setFileUrl(url)
    } catch (error) {
      console.log('Error uploading file: ', error)
    }
  }
  
  // More functions and logic here

The error occurs within this function where it says let event = tx.events[0] and let value = event.args[2]

// Function with error-generating lines
async function createSale(url) {
    const web3Modal = new Web3Modal()
    const connection = await web3Modal.connect()
    const provider = new ethers.providers.Web3Provider(connection)
    const signer = provider.getSigner()

    /* next, create the item */
    let contract = new ethers.Contract(nftaddress, NFT.abi, signer)
    let transaction = await contract.createToken(url)
    let tx = await transaction.wait()
    let event = tx.events[0]
    let value = event.args[2]
    let tokenId = value.toNumber()
    const price = ethers.utils.parseUnits(formInput.price, 'ether')

    /* then list the item for sale on the marketplace */
    contract = new ethers.Contract(nftmarketaddress, Market.abi, signer)
    let listingPrice = await contract.getListingPrice()
    listingPrice = listingPrice.toString()

    transaction = await contract.createMarketItem(nftaddress, tokenId, price, { value: listingPrice })
    await transaction.wait()
    router.push('/')
}

End of the code block

// Return JSX
return (
    <div className="flex justify-center">
      <div className="w-1/2 flex flex-col pb-12">
        <input
          placeholder="Asset Name"
          className="mt-8 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, name: e.target.value })}
        />
        <textarea
          placeholder="Asset Description"
          className="mt-2 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, description: e.target.value })}
        />
        <input
          placeholder="Asset Price in Eth"
          className="mt-2 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, price: e.target.value })}
        />
        <input
          type="file"
          name="Asset"
          className="my-4"
          onChange={onChange}
        />
        {
          fileUrl && (
            <img className="rounded mt-4" width="350" src={fileUrl} />
          )
        }
        <button onClick={createMarket} className="font-bold mt-4 bg-pink-500 text-white rounded p-4 shadow-lg">
          Create Digital Asset
        </button>
      </div>
    </div>
  )
}

Answer №1

The answer provided was remarkably straightforward. All that was required was a minor adjustment to the event word.

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

Error encountered in collision detection on the server side with three.js

Is there a reason why collision detection with three.js behaves differently on the server side compared to the client side, even though they both use the same scene setup? Our goal is to determine collisions with the world on the server side, using a simp ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...

Encountering a 'type error' stating that $(...).modal is not a valid function

While working on a REACT project, I encountered an issue while trying to create and edit a function for updating notes by users using bootstrap modals. The error message that appeared is: Uncaught (in promise) TypeError: jquery__WEBPACK_IMPORTED_MODULE_1__ ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...

An issue has arisen with NextJS Link where it is failing to populate an anchor tag

In my React + NextJS project, I am struggling to display a list of products similar to what you would find on an ecommerce category page. Each product is wrapped in a p tag and should link to its corresponding detail page using an anchor a tag. Although t ...

Updating and removing items from a React state using push and pop methods

I am working on a component in React and have the following state: this.state = { Preferences: [] } I am trying to push an element only if it does not already exist in the array to avoid adding duplicate elements. If the element is already ...

Calculating Object's Position with Velocity Results in NaN

My goal is to have my canvas arcs (representing dog objects) follow the mouse cursor's movements. However, when I check the position or velocity of the objects using console.log, it shows Vector{ x: NaN, y: NaN} A strange observation is that if I di ...

What is the best way to implement client-side data fetching during route transitions using getServerSideProps?

With the release of Next.js 9.3, a new method called getServerSideProps was introduced. Recently, the getInitialProps documentation has been updated to recommend using getStaticProps or getServerSideProps for Next.js 9.3 and newer versions. Although g ...

Initiate the IE driver in WebDriver NodeJS with the option to disregard protected mode settings and possibly introduce flakiness

I'm attempting to create a driver session using IE capabilities to bypass protected mode settings in Internet Explorer, but I'm unsure of the correct syntax. I've experimented with the following: var driver = new webdriver.Builder().wi ...

I am looking to create a function that can trigger a POST request to an API from the web server itself rather than relying on the browser. Specifically, I am working with

Is there a way to create a function that can access an API from within a web server without revealing any details about the API to the browser, including the link? The API call, using the POST method, should be initiated on the server. I am working with N ...

The Ultimate Guide for Formatting JSON Data from Firebase

I'm facing an issue with parsing JSON data returned by Firebase. Here is the JSON snippet: { "-JxJZRHk8_azx0aG0WDk": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda6a68daaa0aca4a1e3aea2a0">[email&# ...

What are the drawbacks of calling async/await within a fresh Promise() constructor?

I have implemented the async.eachLimit function to manage the maximum number of operations concurrently. const { eachLimit } = require("async"); function myFunction() { return new Promise(async (resolve, reject) => { eachLimit((await getAsyncArray ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

"Implementation of clearInterval function may not always result in clearing the interval

The scrolling process within the div element flows smoothly in both directions, however, it seems to encounter an issue when executing the scrollBack() function. Despite including a clearInterval() statement at the intended point, the interval does not a ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

I only notice certain text after carefully inspecting the elements in Google Chrome

While creating an application on Sitefinity (ASP.NET), I encountered an issue where certain elements, such as button text and labels, were not loading correctly when running the application. However, upon inspecting the element, they appeared to be working ...