"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :)

Screenshot: enter image description here Error in text:

 ⨯ app\TicketPage\[id]\page.jsx (30:40) @ foundTicket
 ⨯ TypeError: Cannot read properties of undefined (reading 'foundTicket')
    at TicketPage (./app/TicketPage/[id]/page.jsx:35:45)
  28 |   } else {
  29 |     updateTicketData = await getTicketById(params.id);
> 30 |     updateTicketData = updateTicketData.foundTicket;
     |                                        ^
  31 |   }
  32 |   return <TicketForm ticket={updateTicketData} />;
  33 | };

app\TicketPage[id]\page.jsx:

import TicketForm from "@/app/(components)/TicketForm";

const getTicketById = async (id) => {
  try {
    const res = await fetch(`http://localhost:3000/api/Tickets/${id}`, {
      method: "GET",
      cache: "no-store",
    });

    if (!res.ok) {
      throw new Error(`Failed to fetch Ticket by id ${id} .`);
    }
    console.log("Ah!");
    console.log(res);
    return res.json();
  } catch (error) {
    console.log(error);
  }
};

const TicketPage = async ({ params }) => {
  const EDITMODE = params.id === "new" ? false : true;
  let updateTicketData = {};
  if (!EDITMODE) {
    updateTicketData = {
      _id: "new",
    };
  } else {
    updateTicketData = await getTicketById(params.id);
    updateTicketData = updateTicketData.foundTicket;
  }
  return <TicketForm ticket={updateTicketData} />;
};

export default TicketPage;

app\api\Tickets[id]\route.js:

import TicketForm from "@/app/(components)/TicketForm";

const getTicketById = async (id) => {
  try {
    const res = await fetch(`http://localhost:3000/api/Tickets/${id}`, {
      method: "GET",
      cache: "no-store",
    });

    if (!res.ok) {
      throw new Error(`Failed to fetch Ticket by id ${id} .`);
    }
    console.log("Ah!");
    console.log(res);
    return res.json();
  } catch (error) {
    console.log(error);
  }
};

const TicketPage = async ({ params }) => {
  const EDITMODE = params.id === "new" ? false : true;
  let updateTicketData = {};
  if (!EDITMODE) {
    updateTicketData = {
      _id: "new",
    };
  } else {
    updateTicketData = await getTicketById(params.id);
    updateTicketData = updateTicketData.foundTicket;
  }
  return <TicketForm ticket={updateTicketData} />;
};

export default TicketPage;

i am using node.js v18.16.0, and encountered an issue while updating it. Could this be the cause of the problem?

package.json:

{
  "name": "ticketing-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  // Dependencies section
}

Prior to this, I was using next.js version 14.0.0 and then tried an older version after reading a post about a similar error. The package.json now shows next.js version as 13.0.8, though the actual version installed is Next.js v13.5.6. The YouTuber who created this project used "next": "13.4.13", should I switch to that version?

In an attempt to resolve the issue, I also tried npm install next@canary, but it didn't solve the problem.


i have:

const getTickets = async () => {
  try {
    const res = await fetch("http://localhost:3000/api/Tickets/", {
      cache: "no-store",
    });
    return res.json();
  } catch (error) {
    console.log("Failed to get tickets.", error);
  }
};

This function works perfectly fine, and I use it to display all the tickets. It's puzzling why the getTicketById() function is not functioning properly.

Answer №1

To ensure that the file retrieved by ID exists before accessing the attribute, you can utilize optional chaining:

retrievedData = await getTicketById(params.id);
retrievedData = retrievedData?.foundTicket;

If retrievedData does not exist, this will result in undefined being assigned to it.

Answer №2

Assuming that all is well with the 'getTicketById' function, it seems like the challenge lies in transferring data from RSC to the component without being in JSON format. Consider attempting the following approach:

else {
    const data = await getTicketById(params.id);
    updateTicketData = JSON.parse(JSON.stringfy(updateTicketData));
}

Hopefully this solution resolves the issue.

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

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

Issue with useEffect not correctly applying classNames

Currently tackling a project using Next JS, I've hit a roadblock with React. Here's a simplified version of the code snippet that's giving me trouble. Attempted to reproduce it on codesandbox but couldn't quite nail it down just yet. Wi ...

Changes trigger the re-rendering of inputs

My modal is causing all inputs to be re-rendered with every change I make while typing. I have a Formik object set up like this: const formik = useFormik({ enableReinitialize: true, initialValues: { sp_id: data?.id, ...

Unable to delete data in Laravel 8

I am new to Laravel and facing an issue when trying to delete a row with a modal. The problem is that only the first row is getting removed and I can't figure out the reason. Here is my modal setup: <p class="card-text"><small clas ...

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

Attempt to import Recharts into React was unsuccessful

I am currently exploring the use of recharts in a React project, but I am facing difficulties when trying to import components from its library. I have added it to my package.json file as follows: "recharts": "^2.0.9", However, I am ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

VueJS File Upload Field Failing to Reset Post Successful Submission

I am facing an issue in my VueJS application where the form does not clear all field values after submission, especially the file upload field. After a successful submission, the uploaded file name still remains displayed on the screen. Below is the code ...

Is it possible to import a global package in Node if NODE_PATH is already configured?

Currently, I am encountering an issue with trying to import a globally installed package that is located at /some/path. To address this problem, I have configured NODE_PATH in my ~/.bash_profile and confirmed its existence by running 'echo $NODE_PATH& ...

When the model is replaced, the Vue.js directive v-html may fail to update

Upon running the code below (a Vue.js component), my expectation is that both the v-html directive and the console.log() will display the same value after the AJAX call returns. To my surprise, while v-html remains stuck at "loading...(1)", the value of o ...

Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message: ReferenceError: localStorage is not defined Here is my store configuration: const store = createStore(r ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

Tips for adjusting the size of an HTML canvas to fit the screen while preserving the aspect ratio and ensuring the canvas remains fully visible

I'm working on a game project using HTML canvas and javascript. The canvas I am using has dimensions of 1280 x 720 px with a 16:9 aspect ratio. My goal is to have the game displayed at fullscreen, but with black bars shown if the screen ratio is not 1 ...

How to Utilize Muuri Javascript Library with Bootstrap Tabs: Resizing Required for Expansion?

Struggling for days and feeling frustrated, I'm hoping someone can help me crack this mystery. My idea is straightforward - three Bootstrap 4 tabs with drag and drop functionality inside each, all displayed in a responsive stacked masonry layout. To a ...

What is the significance of a window's "o" condition?

Recently, I came across a code snippet that looks like this: if (!('o' in window)) { o = "somelink"; l =["n", "somelink"]; p = [0.8,1]; d = new Date("2018/01/01"); if (Date.now() >= d) { r = Math.random(); v ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Utilizing HTML/CSS with React/Bootstrap: A Comprehensive Guide

Looking for help with integrating HTML/CSS code into React/Bootstrap? I need assistance with coding in React using Bootstrap. How do I effectively use components and props? Even after installing bootstrap, I am encountering errors. Is it possible to dire ...

Making an HTTP request within a forEach function in Angular2

Encountering an issue while using the forEach function with HTTP requests. The _watchlistElements variable contains the following data: [{"xid":"DP_049908","name":"t10"},{"xid":"DP_928829","name":"t13"},{"xid":"DP_588690","name":"t14"},{"xid":"DP_891890" ...