Search code examples
reactjsreact-reduxmern

How can I get the date to show when component is first rendered? MERN stack


I've created a form the user fills out, and then can update. When the form renders to update, the date that is stored in the user's database entry won't show up. I get this error: The specified value "Mon Jul 27 1987 20:00:00 GMT-0400 (Eastern Daylight Time)" does not conform to the required format, "yyyy-MM-dd"

I have another form, and it seems to work just fine, but for some reason this form won't load the date upon rendering.

This is how the date is set when the form is originally submitted and updated:

<div>
   <label>Date of birth</label>
   <input name="dateOfBirth" label="Date of birth" type="date" value={dateOfBirth} onChange={(e)=> setDateOfBirth(e.target.value)} />
</div>

and this is how the state is loaded:

const HHForm = ({user, userState}) => {

    const [dateOfBirth, setDateOfBirth] = useState(userState?.healthHistory[0]?.dateOfBirth ? ((userState?.healthHistory[0]?.dateOfBirth) : (''))

But when the component renders to update the form, the date is just left as an empty date selector, as if there is no date data, but the database has an entry for the dateOfBirth.


Solution

  • HTML 5 date pickers should be in format of yyyy-MM-dd. You should format your date. You can use moment to do that. https://www.npmjs.com/package/moment

    import moment from 'moment'
    
    setState(moment(your date here).format('YYYY-MM-DD'))
    

    Here is full code https://codesandbox.io/s/date-picker-76lgw?file=/src/App.js