-1

I am trying to add a dynamic list to my Expanse List and am getting this error while doing it:

**TypeError: Date.getFullYear is not a function**

[TypeError: Date.getFullYear is not a function on ReactJs ][1]

but in a static list, it shows me the format as I wanted with no error.

This is a static list:

This is a static list

I am trying to update the list depending on user input.

Expanse.js

  return (
    <div>
      <Wrapper>
        <DateAndTitle>
          <ExpanseTime>
            <ExpanseDates Date={date} />
          </ExpanseTime>
          <Title>{title}</Title>
        </DateAndTitle>
        <Amount>{amount}$</Amount>
      </Wrapper>
    </div>
  );
};

ExpanseDate.js


  let month =Date.toLocaleString("en-US", { day: "2-digit" });
  let day = Date.toLocaleString("en-US", { month: "long" });
  let year = Date.getFullYear();


  return (
    <Wrapper>
     <ExpanseDays>{day}</ExpanseDays>
      <ExpanseMonth>{month}</ExpanseMonth>
      <ExpanseYear>{year}</ExpanseYear>

    </Wrapper>
  );
};

AddExpanse.js

This is User Input:

This is User Input

The is userInput code :

enter image description here

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
Idriss
  • 617
  • 1
  • 4
  • 14

4 Answers4

1

/*** even though an input element attribute has date type, it always returns a string value, So, inside your Form component, you must first convert the entered input string date to this date format 'Sun Dec 05 1999 00:00:00 GMT+0530 (India Standard Time)'. Reason : in some DateComponent, that input value is considered as date and you have applied Date object's related method. ex: [inputDate.toLocaleString("en-US", { month: "long" })] **/

/form component**/

const defaultUserInput = {
  title: "",
  amount: "",
  date: "",
};


const ExpenseForm = ({ onSaveExpenseData }) => {
    
    const [userInput, setUserInput] = useState(defaultUserInput);
    const { title, date, amount } = userInput;
  
    const changeHandler = (event) => {
      const { value, name } = event.target;
  
      setUserInput((prevState) => {
        if (name === "date") {
          const [y, m, d] = value.split("-").map((s) => parseInt(s, 10));
          return { ...prevState, [name]: new Date(y, m - 1, d) };
        }
        return { ...prevState, [name]: value };
      });
    };
  
    const SubmitHandler = (event) => {
      event.preventDefault();
      onSaveExpenseData(userInput);
      setUserInput(defaultUserInput);
    };
  
    return (
      <form onSubmit={SubmitHandler}>
        <div className="new-expense__controls">
          <div className="new-expense__control">
            <label>Title</label>
            <input
              type="text"
              onChange={changeHandler}
              name="title"
              value={title}
            />
          </div>
          <div className="new-expense__control">
            <label>Amount</label>
            <input
              type="number"
              min="0.01"
              step="0.01"
              onChange={changeHandler}
              name="amount"
              value={amount}
            />
          </div>
          <div className="new-expense__control">
            <label>Amount</label>
            <input
              type="date"
              min="2019-01-01"
              max="2022-01-01"
              onChange={changeHandler}
              name="date"
              value={date}
            />
          </div>
        </div>
  
        <div className="new-expense__actions">
          <button type="submit">Add Expense</button>
        </div>
      </form>
    );
  };
  
  export default ExpenseForm;
 

/date component**/

const ExpenseDate = ({ date }) => {
   
  const month = date.toLocaleString("en-US", { month: "long" });

  const Itemdate = date.toLocaleString("en-US", { day: "2-digit" });

  const year = date.getFullYear();

  return (
    <div className="expense-date">
      <div className="expense-date__month">{month}</div>
      <div className="expense-date__day">{Itemdate}</div>
      <div className="expense-date__year">{year}</div>
    </div>
  );
};

export default ExpenseDate;
1
const [dateUpdate, setDateUpdate] = useState("");
const [nameUpdate, setNameUpdate] = useState("");
const [priceUpdate, setPriceUpdate] = useState("");     

//In function (it might be your submit button in your form component)

const dataShow = {
      title: nameUpdate,
      amount: priceUpdate,
      date: new Date(dateUpdate),
    };

//Make sure you use new Date(dateUpdate) instead of date: dateUpdate
Ritika Sharma
  • 87
  • 1
  • 2
0

Try this:

const now = new Date();
let month = now.toLocaleString("en-US", { day: "2-digit" });
let day = now.toLocaleString("en-US", { month: "long" });
let year = now.getFullYear();
davood Sandoghsaz
  • 674
  • 1
  • 4
  • 13
0

Edit:

You still haven't provided a reproducible example or all of the dependent code in your app, but now I think that you are passing a string to the Date property of your ExpanseDates component instead of an actual Date.

If you are using a date input to get a date value, you'll need to parse the value of the input into an actual JavaScript date object before passing it to that component:

function getDateFromInput (input) {
  const [y, m, d] = input.value.split('-').map(s => parseInt(s, 10));
  return new Date(y, m - 1, d);
}

function handleChange (ev) {
  const date = getDateFromInput(ev.target);
  // use the date: just logging it to console here
  console.log(date.toString());
}

document.querySelector('input[type="date"]').addEventListener('input', handleChange);
<input type="date" value="1999-12-31" />

The example you've shown is incomplete and can't be used to reproduce your error. However, here's a snippet which includes relevant portions in your question, demonstrating how to destructure a value from a component's props:

In the case of your code, the property's name happens to be Date, which is the same name as the builtin Date class in JavaScript and shadows it in the scope of the component. This is generally not a good practice: it's not a good idea to shadow built-ins.

Try renaming that prop in your ExpanseDates component to avoid ambiguity with the builtin Date.

<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

function Component (props) {
  const {Date} = props;
  let day = Date.toLocaleString("en-US", { day: "2-digit" });
  let month = Date.toLocaleString("en-US", { month: "long" });
  let year = Date.getFullYear();
  return <div>{year} {month} {day}</div>;
}

function Example () {
  const date = new Date();
  return <Component Date={date} />;
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • yes i did your suggestion but some how i still get **TypeError: Date.getFullYear is not a function** here is the error : https://imgur.com/a/2lyb5TN – Idriss Dec 05 '21 at 16:24
  • @Oulili It looks like you still haven't renamed that property on your component's `props`. Try changing the name from `Date` to `date` (lowercase `d`). – jsejcksn Dec 05 '21 at 16:26
  • Thanks For answering yea i change it to d lowecase the static page shows me this: https://imgur.com/a/8MKbEVl , it's means it's working but when i hit submite button it's gives me : date.getFullyear() is not a function i texted on on twitter if you want all souce code – Idriss Dec 05 '21 at 16:33
  • We can't help you debug without a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – jsejcksn Dec 05 '21 at 16:36
  • okay i will try – Idriss Dec 05 '21 at 16:38
  • @Oulili See my updated answer. – jsejcksn Dec 06 '21 at 08:28
  • Hi again i find the problem when i useState to store data from user input in an object it's was like this obj ={ date = dateex} i forget to parse the date using date:new Date (datexx) – Idriss Dec 06 '21 at 16:29