In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself needing to reset this value.
This is how the document suggests using the component:
static defaultProps = {
date: new Date()
timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
};
state = {
date: this.props.date,
timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};
onDateChange(date) {
this.setState({date: date});
};
render(){
return(
<View style={styles.wrap}>
<View style={styles.datePickerIOS}>
<DatePickerIOS
date={this.state.date}
mode="time"
timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
onDateChange={this.onDateChange.bind(this)}
minuteInterval={10}
/>
</View>
I attempted to use props and save this data to local storage.
static defaultProps = {
date: new Date()
timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
};
state = {
date: this.props.date,
timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};
componentWillMout() {
this.props.updateDate(this.props.date)
}
onDateChange(date) {
this.setState({date: date});
this.props.updateDate(date)
};
render(){
return(
<View style={styles.wrap}>
<View style={styles.datePickerIOS}>
<DatePickerIOS
date={this.props.alarmConfig.date}
mode="time"
timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
onDateChange={this.onDateChange.bind(this)}
minuteInterval={10}
/>
</View>
The function updateDate(date) is an action:
export function updateDate(date){
return {
type: "UPDATE_DATE",
date: date,
}
}
export function alarmConfig(state=initialState, action){
switch(action.type) {
case types.UPDATE_DATE:
return {
...state,
date: action.date
};
When following this approach, the value under alarmConfig.date turns into a string, resulting in an error as the DatePickerIOS Date prop requires a Date type.
If I simply make the change below:
<DatePickerIOS
date={this.state.date}
mode="time"
timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
onDateChange={this.onDateChange.bind(this)}
minuteInterval={10}
/>
Both the value under alarmConfig.date and state.date become Dates again.
What could be causing this situation? And how can I modify the code to achieve my goal?
I appreciate everyone's input.