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