Console.log(appointment[0].apps.date) gives a date, but I get 'Cannot read property 'date' of undefined' when I use it in my function

I keep getting Cannot read property 'date' of undefined when I call my getDataPrevDay function, but console.log(appointment[0].apps.date) logs 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 is the handler

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);
});

1 answer

  • answered 2021-06-23 07:29 Trishant Pahwa

    The prop is rendered and updated dynamically. You can add a fail safe to avoid uniterable values by skipping if they are null.

    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
        },
    };}