Error: Unable to access the 'then' property of an undefined object when working with promises

I'm developing a website project that serves as a "Walmart" version of AirBnB.

Here's the functionality of the button in question:

When a user clicks on the "Make Reservation" button on a listing, they are prompted to select a start and end date before submitting. This action triggers an HTTP request to the server.

Unfortunately, I've encountered an error message that reads:

TypeError: Cannot read property 'then' of undefined at /vagrant/LightBnB/LightBnB_WEB_APP/server/apiRoutes.js:44:7 <--

The problematic API route is located at line 44:7 which is as follows:

This section of code is causing the issue:

.then((reservation) => {
            res.send(reservation);

The API ROUTE Logic responsible for the problem is illustrated below:

  router.post('/reservations', (req, res) => {
    const userId = req.session.userId;
    database
      .addReservation({ ...req.body, guest_id: userId })
      .then((reservation) => {
        res.send(reservation);
      })
      .catch((e) => {
        console.error(e);
        res.send(e);
      });
  });

This route invokes the addReservation() function defined as follows:

    /**
 * Add a reservation to the database
 * @param {{}} reservation An object containing all of the reservation details.
 * @return {Promise<{}>} A promise to the reservation.
 */
const addReservation = function (reservation) {
  const queryString = `
  INSERT INTO reservations(
    start_date,
    end_date,
    property_id,
    guest_id 
  ) 
  VALUES ($1, $2, $3, $4)
  RETURNING *
  `;
  const values = [
    reservation.start_date,
    reservation.end_date,
    reservation.property_id,
    reservation.guest_id,
  ];
  pool
    .query(queryString, values)
    .then((res) => {
      res.rows;
    })
    .catch((e) => console.log(e.message));
};
exports.addReservation = addReservation;

If you require further information, please feel free to ask.

Answer №1

A TypeError has occurred: Unable to read property 'then' of undefined

The function addReservation() does not have a return value, resulting in undefined being returned. Therefore, attempting to use addReservation(...).then(...) leads to an attempt to access .then() on undefined, causing the error.

In the implementation of addReservation(), make sure to modify:

pool.query(...).then(...).catch(...)

to

return pool.query(...).then(...).catch(...)

This allows the promise to be returned so that the caller can utilize .then() on the promised result.


Furthermore, the .catch() handler within addReservation() is currently logging and dismissing the error. It would be more helpful to rethrow the error for the caller to see:

Replace this:

.catch((e) => console.log(e.message))

with this:

.catch((e) => {
     console.log(e.message)
     // re-throw the error to pass it up
     throw e;
})

It should also be noted that using res.send(e) may not provide significant information as most properties of the Error object are non-enumerable and will not be displayed when res.send() converts the Error object into JSON format.

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

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load. In addition to disabling buttons, I also aim to deactivate all links on th ...

Activate the dialog box exclusively after data has been submitted via the submit button on a form

My goal is to create a data saving functionality with a next button. After filling out the form, clicking on the next button triggers a popup dialog asking, "Do you want to submit your data?" To achieve this, I included the following code in my submit but ...

Utilizing React to create an infinite loop, where an onClick event triggers an image change that updates the source of

I'm experiencing an infinite loop in my React application. I'm attempting to include a previous Image and next Image button in the development stage using an image tag. However, when my component loads up, I encounter errors. Does anyone have a ...

While in the process of developing a React application, I have encountered the following challenge

PS F:\Programming Tutorials Videos\R Practice> npx create-react-app custom-hook npm ERR! code ENOTFOUND npm ERR! syscall getaddrinfo npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.npmjs.org/create-react-app failed, reaso ...

Turn off email alerts for items and folders in ALFRESCO 5.2

Here's a snippet of JS code I created to toggle notifications with a button click: (Action.min.js): var me = this, jsNode = record.jsNode, content = jsNode.isContainer ? "folder" : "document"; if (jsNode.hasAspect("cm:emailed") ...

How to drag an item onto another element using Vue.Draggable without the need for adding or removing

Are you familiar with the library https://github.com/SortableJS/Vue.Draggable? I am trying to achieve a drag and drop functionality where I can drag a file into a folder. However, I am facing an issue as the @change event only provides data about the drag ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

Preventing pageup/pagedown in Vuetify slider: Tips and tricks

I am currently using Vuetify 2.6 and have integrated a v-slider into my project. Whenever the user interacts with this slider, it gains focus. However, I have assigned PageUp and PageDown keys to other functions on the page and would like them to continue ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

I've encountered a peculiar error that is new to me while using bootstrap and javascript. Can anyone shed light on what this error signifies?

Hey there! I've come across this error in the console while attempting to utilize Bootstrap. It seems that a style is being refused from 'http://127.0.0.1:5500/node_modules/font-awesome/css/font-awesome.min.css' due to its MIME type ('t ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

Distinguishing between findOneAndDelete() and findOneAndRemove()

I am struggling to understand the difference between findOneAndDelete() and findOneAndRemove() functions in the mongoose documentation. Query.prototype.findOneAndDelete() There is a slight difference between this function and Model.findOneAndRemove(). ...

What is the process for modifying the characteristics of an RMWC Component?

How can I dynamically change the icon attribute in my RMWC Button element when an onClick event occurs? <Button outlined icon={<CircularProgress />} onClick={(e)=> { // e.currentTarget.icon = ''; // console.log(e.c ...

Guide to utilizing an Ajax response object

Here is the code I am using to display data based on values selected from dropdowns: $("#botao-filtrar").click(function(){ $(".mask-loading").fadeToggle(1000); $.ajax({ url: 'datacenter/functions/filtraDashboardGeral.php', as ...

Discover the secrets to unlocking IntelliSense for Express.js in Visual Studio Code

After attempting to install type definitions using: The javascript file where my code is located is server.js. npm install @types/express Unfortunately, I am still not receiving intellisense for the 'app' variable after initializing express. ...