Jon Nicholson
Jon Nicholson

Reputation: 1131

Setting date input to initial value pulled from database

I'm currently storing a date in my database in the following format:

2021-05-07T00:00:00.000Z

I'm wanting to take this value in my React app and place it as the value within my date input when the component first loads.

However, it just keeps defaulting to today's date.

I can't figure out what I'm doing wrong - can anyone point out how I should refactor my code so that the date mentioned above is passed in to the initial value of my date input?

For reference - the parent component manages the date state, and this is passed down as props. The state value is like mentioned above.

Second reference - the value is definitely getting passed down, as console logs of 'dueDate' show the above value.

const CalendarDates = ({ dueDate, setDueDate }) => {

    const handleChange = (event) => {
        setDueDate(event.target.value)
    }

    return (
        <div className="calendar-dates-container">
            <div className="calendar-due-date">
                <i className="fas fa-calendar-week"></i>
                <input value={dueDate} type="date" onChange={handleChange} />
            </div>
        </div>
    )
}

Upvotes: 0

Views: 75

Answers (1)

Someone Special
Someone Special

Reputation: 13588

input with type="date" expects date format to be YYYY-MM-DD

So if your dueDate is in the format of 2021-05-07T00:00:00.000Z, you need to first convert it to YYYY-MM-DD

Converting date string to YYYY-MM-DD

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}
 
console.log(formatDate('2021-05-07T00:00:00.000Z'));

With the above snippet, you can end up with something like this.

const CalendarDates = ({ dueDate, setDueDate }) => {

    const handleChange = (event) => {
        setDueDate(event.target.value)
    }

    const date = useMemo(() => {
        return formatDate(dueDate)
    },[dueDate])

    return (
        <div className="calendar-dates-container">
            <div className="calendar-due-date">
                <i className="fas fa-calendar-week"></i>
                <input value={date} type="date" onChange={handleChange} /> 
            </div>
        </div>
    )
}

In your backend, you will then convert YYYY-MM-DD to your desire date string to be stored in your database.

Upvotes: 3

Related Questions