Consider this JSON structure, which is returned by a server AJAX request:
{
"Items": [
{
"ID": 1,
"Name": "John Smith"
},
{
"ID": 2,
"Name": "Jane Doe"
}
]}
And a Fetch function that sets the JSON data into the state of a view component:
FetchData(json => {
this.setState({
Items: json.Items,
})
})
Further down the component tree there is a React component with a checkbox, whose render() method looks like this:
render(){
return (
<input type="checkbox" checked={this.props.Item.IsSelected} onClick={this.handleToggleItemEvent.bind(this)} />
<span>{this.props.Item.Name}</span>
);
}
The main view component has a handleToggleItemEvent that is responsible for setting the IsSelected state of the item:
handleToggleItemEvent(ID){
var item = _.find(this.state.Items, item => {
return item.ID === ID;
});
if(item){
item.IsSelected = !item.IsSelected;
this.setState({
items: this.state.Items
});
}
}
If the checkbox for the first item is clicked, the object will look like this:
{
"Items": [
{
"ID": 1,
"Name": "John Smith",
"IsSelected": true
},
{
"ID": 2,
"Name": "Jane Doe"
}
]}
Because the IsSelected state is internal to the application and not returned from the server, when I fetch the data again (say by filtering the data), the IsSelected property will go away. What is the best way to merge this data together (or is this just a bad idea entirely)? I have seen the Immutability Helpers, but I am not sure how I can use them to merge properties for each element in the array.