"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

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

Managing the re-triggering of a function within useEffect upon the user clicking the "Back Button" in a React application

Is there a way to prevent the loadUserPosts() function from being called again when the user clicks the 'back button' on their browser? It seems like the isLogged useState is being changed when the back button is clicked. The loadUserPosts funct ...

Incorporating multiple web services into a React JS project to populate a Material UI dropdown efficiently

I have some code that is calling a web service and I have a few questions. Firstly, what is the best way to call a second web service? Currently, I am calling one and displaying the data in a list. But if I need to call a second web service, should I also ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...

employing document.write() specifically for a designated division

This is the coding: $(document).ready(function(){ var Jstr = { "JSON" : [ { "Eid" : 102,"Ename":"", "Ecode" : "<input type ='text'/>", "Eprops": {"name": "", "value":"", "maxlength":""}} ] } ; $(".search").click(funct ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Tips for creating a drawing grid with a table

I am currently working on a project where I need to create a canvas-like table with around 10,000 cells. The goal is to allow users to draw on this canvas by moving their mouse over it while holding down specific keys (e.g. ctrl for blue, shift for red). ...

What is the method for obtaining the values from these newly generated text fields?

Every time I click on the "ADD TEXTBOX" button, a new HTML textbox is dynamically created using jQuery's append method. However, I am struggling to figure out how to retrieve and store the values of these textboxes in PHP. $(w).append('<div&g ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

Adjust the z-Index of the list item element

I am attempting to create an effect where, upon clicking an icon, its background (width and height) expands to 100% of the page. However, I am struggling with ensuring that the 'effect' goes underneath the this.element and above everything else. ...

What is the best way to transform a JavaScript object into an array?

Here is the information I have: {product_quantity: {quantity: 13, code: "AAA", warehouse: "1000",}} The product_quantity field is part of a JSON object in a MongoDB database. I am looking to convert it into this format: {"produ ...

How to update the state of a component in the root layout from its child components in Next JS 13 with the app router?

I am in the process of upgrading a Next JS app project to utilize the App Router. Within the layout.js (the root layout), there is a Logo component that will be visible on all routes. Within the RootLayout, I am managing a state variable to modify the ap ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

Tips for saving the circular slider value to a variable and showcasing it in the console

I have coded a round slider and need assistance with storing the slider value in a variable and displaying it in the console using JavaScript. I want to store the tooltip value in a variable for future use. $("#slider").roundSlider({ radius: 180, min ...

Utilizing Express.js: Implementing a Route that is Outside the Current Router

app.js: var app = express(); app.use('/my-page', require('./routes/my-page.js')); my-page.js: const router = require('express').Router(); router.get('/one', function (req, res, next) { return res.send('thi ...