samedi 26 juin 2021

Data not being set to default values

When I call the getDataPrevDay function I get an error: "Cannot read property 'apps' of undefined." console.log(doc) logs [], but doc is supposed to be set to dataModel if it's undefined or null. When I change the handler code if(doc.first_name == undefined || doc.first_name == null) it just sets doc to dataModel always, even if there is data that can be fetched from the database

handler.get(async (req, res) => {
  const {date} = req.query;

  const dataModel = 
 [{
  'first_name': 'no data',
  'last_name': 'no data',
  'number': 'no data',
  'email': 'no data',
  'date': date,
  'time': 'no data'
}];


let doc = [];
if(date) {
  doc = await req.db.collection('db').find({date: date}, {projection : {_id: 0}}).toArray();
} 
if(doc == undefined || doc == null) {
  doc = dataModel;
}

res.json(doc);
});

This is how it's called

const admin = ({data}) => {
    const [appointment, setAppointment] = useState(data);

    let currentDate = moment(appointment[0].apps.date).format("YYYY, MMM, DD")
    

    const getDataPrevDay = async () => {
        let prevDay = moment(currentDate).subtract(1, "day").format("YYYY, MMM, DD");

        const res = await fetch(`http://localhost:3000/api/usersdb?date=${prevDay}`)
        let json = await res.json();
        json = json.map(apps => ({apps}))
        setAppointment(json)
    }


...

return (
<button className={styles.button} onClick={getDataPrevDay}> Previous Day </button>
)

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

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

export default admin



Aucun commentaire:

Enregistrer un commentaire