I'm displaying 2 select dropdown's, one displaying a start hour, one displaying an end hour. Both states start_hours
and end_hours
uses data imported from the same file. I wanted so that when user selects a start hour, the end hour will only display hours AFTER the selected start hour. However, while trying to filter/disable the previous end_hours
, the start_hours
became affected as well.
The only way I was able to achieve my results is creating a duplicate file with the same data, give it a different import name, and setting it to the initial state. This is incredibly redundant and I am sure there is a cleaner way to do this.
times.js
export default [
{
"time": "07:05",
"display": "07:05 AM",
"disabled": false
},
{
"time": "07:0",
"display": "07:10 AM",
"disabled": false
},
{
"time": "07:15",
"display": "07:15 AM",
"disabled": false
},
App.js:
import React from 'react';
import hours from './data/hours';
....
...
constructor(props) {
super(props);
this.state = {
start_hours: hours,
end_hours: hours
};
}
....
.....
onStartHourClick(e) {
....
....
let endTime = this.state.end_hours, state = Object.assign({}, this.state);
this.state.end_hours.map((time, index) =>{
if(Date.parse(`${day} ${e.target.value}`) >= Date.parse(`${day} ${time.time}`)) {
state.end_hours[index].disabled = true;
}
});
this.setState({state});
}
The code I wrote successfully filters/disables previous hours but it is ALSO doing it on the start_hours
thus making both state objects identical. The only way I was able to achieve end_hours
being filtered out ONLY was importing the SAME json file twice:
import hours from './data/hours';
import hours2 from './data/hours2';
...
...
constructor(props) {
super(props);
this.state = {
start_hours: hours,
end_hours: hours2
};
}