Search code examples
javascriptreactjsreact-hooksundefined

React mapping ERROR: Cannot read properties of undefined (reading 'toLocaleString')


Im trying to map the list of my expense array elements and after using the map() method Im getting the error "Uncaught TypeError: Cannot read properties of undefined (reading 'toLocaleString')". I couldn't find the issue please check the code link - https://github.com/mohitdevelops/react-lessons/tree/main/toLocalString-issue

Please help me out, I'm stuck in this error for days.

And checkout the screenshot here 👇

enter image description here


Solution

  • You're using the wrong object keys in your expenseData object in the ExpenseForm component. And so the date will "always" be undefined thus failed during the date conversion in your ExpenseDate component. To fix this, you just need to supply the correct object:

    From this:

    const expenseData = {
        inputValue: enteredValue,
        inputAmount: enteredAmount,
        inputDate: new Date(enteredDate),
    };
    

    To this:

    const expenseData = {
        id: "e5", // You will need to figure out a way to create a dynamic ID here :)
        title: enteredValue,
        amount: enteredAmount,
        date: new Date(enteredDate),
    };