adrian95999
adrian95999

Reputation: 115

Problem with saving data with react-datetime inside Formik component

I'm trying to change my default datepicker to DateTime. I'm using Formik and I know that this is a problem with custom inputs. For now when I'm saving changes form is being saved, but with current date, not with the one that I choosed. Any ideas how to fix this? My code (part with datepicker) for now:

<Datetime
    id="dateFrom"
    name="dateFrom"
    placeholder="Enter date"
    value={this.props.dateFrom}
    onChange={this.props.onChange}
    onBlur={this.props.onBlur}
    isInvalid={!!this.props.errors.dateFrom}
    readOnly={this.props.status !== ProjectStatus.InProgress}
 />

Value was this.props.dateFrom before, bacause the same component is showing up when editing existing entry.

Upvotes: 2

Views: 3589

Answers (2)

symnetry lamp
symnetry lamp

Reputation: 11

i find another solution in render like this

<Field
    name="time"
    render={({field,form:{isSubmitting}})=>(
        <Datetime onChange={time=>{setFieldValue('time',time.format('YYYY-MM-DD'))}}/>
    )}
/>

CodeSandbox

Upvotes: 1

adrian95999
adrian95999

Reputation: 115

I was doing researches, trying different approaches and asked for help of other developers. I came up with this solution, which works for me:

<Datetime
    id="dateFrom"
    name="dateFrom"
    placeholder="Enter date"
    value={this.props.dateFrom}
    onChange={(dateFromValue) => {this.props.setFieldValue('dateFrom', this.formatDate(dateFromValue))}}
    onBlur={this.props.onBlur}
    isInvalid={!!this.props.errors.dateFrom}
    readOnly={this.props.status !== ProjectStatus.InProgress}
/>

And formatDate function:

formatDate(momentDate) {        
    return moment(momentDate).format("YYYY-MM-DD");
}

Upvotes: 4

Related Questions