When I use Console.log(appointment[0].apps.date), I receive a date as expected. However, when I attempt to use this date in my function, I encounter the error 'Cannot read property 'date' of undefined'

Every time I try to call my getDataPrevDay function, I keep getting the error message "Cannot read property 'date' of undefined." Strangely enough, when I log

console.log(appointment[0].apps.date)
, it shows the correct date.

const admin = ({data}) => {

const [appointment, setAppointment] = useState(data);

console.log(appointment[0].apps.date)

const getDataPrevDay = async () => {
    let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
    let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
    const res = await fetch(`http://localhost:3000/api/appointmentsdb? 
    date=${newDate}`)
    let json = await res.json();

    setAppointment(json);
}

....

return (
  <button onClick={getDataPrevDay}> Prev Day </button>
 )
}

export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))

return {
    props: {
        data: json
    },
};}

This snippet below is the handler function:

handler.get(async (req, res) => {
const {date, first_name, last_name, number, email, time} = 
req.query;
const dataModel = 
  {'_id': new ObjectID(), 
  'first_name': first_name,
  'last_name': last_name,
  'number': number,
  'email': email,
  'date': date,
  'time': time
  };

let doc = {}

if(date) {
  doc = await req.db.collection('Info').find({date: date}, 
 {projection : {_id: 0}}).toArray()
} else {
  doc = await req.db.collection('Info').findOne()
} if(doc == null) {
  doc = dataModel;
} 
 res.json(doc);
});

Answer №1

This component dynamically renders and updates the prop. To prevent errors with iterable values, a fail-safe has been included to skip null values.

const admin = ({data}) => {

const [appointment, setAppointment] = useState(data);

console.log(appointment[0].apps.date)

const getDataPrevDay = async () => {
    if(appointment && appointment.length && appointment[0].apps && appointment[0].apps.date) {
        let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
        let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
        const res = await fetch(`http://localhost:3000/api/appointmentsdb? 
    date=${newDate}`)
        let json = await res.json();

        setAppointment(json);
    }
}

....

return (
  <button onClick={getDataPrevDay}> Prev Day </button>
 )
}

export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))

return {
    props: {
        data: json
    },
};}

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

Combining the power of Kendo UI with the flexibility of Vue

Hey there everyone, I'm currently utilizing the Vue.js CLI for my project. Recently, I came across a helpful tutorial on incorporating a Jquery plugin into a webpack project at this link: . To achieve this, I installed the expose loader and added th ...

What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button. function addNewItem() { //ADD ROW AND CLONE var table = document.getElementById('tbl'); var tbody = document.create ...

Is there a way for me to determine the exact coordinates of all buttons on a given webpage?

I came across this piece of code, but I'm a bit unsure about where exactly I should input it and how to adjust it to locate the position of each button. Additionally, I'm curious as to where the results (coordinates) will be shown? function find ...

What steps can I take to optimize this Vue Js code without relying on local storage?

I'm working on implementing authentication for a Vue.js and Auth0 application. Currently, I have a code snippet that uses local storage to store and retrieve values like `expiresAt`, `idToken`, `accessToken`, and `user`. How can I refactor this code t ...

Why does WebdriverIO send a POST request for an unused webelement?

Exploring the capabilities of webdriverIO has been quite enjoyable! There are many features of this framework that I already appreciate. In my investigation, I wanted to see how WebdriverIO handles non-existing elements and lazy element loading in this te ...

Encountering a problem while integrating Vuetify into a Vite project

After setting up a Vite project, creating a navigation component, and implementing a router, I decided to integrate Vuetify into the project using npm i vuetify. However, I encountered the following error: Uncaught Error: [Vuetify] Could not find injected ...

A pair of iterations of the same design

It may sound strange, but I find myself in a situation where I need to have two versions of the same model in my Node.js application. Let me try to explain. I am required to create two different account types, one for job seekers and one for employers. Th ...

Transferring a JSON document to an Express server with JavaScript

I've recently started learning JavaScript and I'm facing an issue with sending a JSON file to my server (Express) so that I can parse its contents and use them in the web application I'm developing. Here's my current setup: a JSON fil ...

Steps for implementing a select all feature with jQuery

I'm currently working on a jQuery function that is acting as a select-all option. Everything is functioning correctly except that when I deselect any of the child elements from select all, the option remains enabled. My goal is to enable or disable th ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Hiding a row in AngularJS after changing its status can be achieved by utilizing the

I need help hiding a clicked row after changing its status using angularjs. Below is the code I have written, can someone guide me on how to achieve this? table.table tr(data-ng-repeat="application in job.applications", ng-hide="application.hideApplic ...

I'm having trouble locating the subgenerator for the Yo generator. During an NPM installation, it appears that not all of the code is being downloaded

I am in the process of developing a Yo generator for creating hapijs modules. I have already published it to NPM, but when I install it in a new project using npm install generator-hapijs, not all the code is downloaded into my node_modules/generator-hapij ...

Best practices for defining TypeScript types

In my quest to optimize my TypeScript type definitions, I have scoured countless pages for the best approach. In the past, I kept a typings.ts file tucked away in my project, importing types into each file as needed using: import {IMyCustomType} from &a ...

Obtain Attribute Value Using JQuery

I am trying to extract the value from this attribute element, but I am unsure of the correct way to do it. Can someone help me out? Here is the code snippet: <select name="Hello/1.0/TestWorld" size="1" disabled="disabled" ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Issue with AJAX functionality in CodeIgniter causing errors

I am facing an issue with Ajax in CodeIgniter. The alert message within the script works perfectly fine, but for some reason, the controller function is not being called. View section: <div class="col-md-6 col-sm-6 col-xs-12"> <a class="butt ...

Embed full content in iframe using bootstrap 4

Embedding an iframe of an appointment scheduling frontend on my page has been a challenge. While the width is correct, the height of the frame is too small. Despite attempting various CSS modifications, I have not been able to achieve the desired result. I ...

Newly imported App component not appearing in App JS after import

Whenever I add a new component called cart.js in the app.js file, the app stops rendering anything on the browser without throwing any errors. Surprisingly, the modal.js code is also shared here as it acts as a wrapper for the cart component. Interestingly ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...