I have a dropdown menu where I can select multiple items. And everytime I choose an item from the dropdown, it is being saved in the localStorage. Upon reloading the browser, I want the selected item to still display in the dropdown selection, since it is saved in the localStorage. here is an image of the dropdown menu as you can see here, it is being saved on the localStorage
this is the code I used to save to localStorage:
handleWellChange: function(){
if (!check_modify_load) {
if ($("#selectWell").val()) {
var w_id;
var select_well = $("#selectWell").val();
var w_id_arr = this.state.w_id_arr;
if ($("#selectWell").val().length == 1 && !this.state.unselect) {
$( "#loading" ).fadeIn( "fast" );
this.props.getData($(".select2-selection__choice").attr("title"), select_well[0])
} else if (w_id_arr.length < select_well.length) {
$( "#loading" ).fadeIn( "fast" );
var w_id = $(select_well).not(w_id_arr).get();
this.props.getData("", w_id, true);
}
this.setState({ w_id_arr: select_well })
this.state.unselect = false;
localStorage.setItem("select_well", JSON.stringify(select_well));
console.log('Yow', select_well)
} else {
this.props.clearTable();
}
}
else {
check_modify_load = false
}
},
this is the code to getItem from localStorage:
componentDidMount:function(){
var select_well = JSON.parse(localStorage.getItem("select_well")) || [];
console.log('EYY', select_well)
console.log(typeof(select_well))
this.setState({'select_well': select_well})
$('#selectWell').on('select2:unselect', function (evt) {
if ($("#selectWell").val() && $("#selectWell").val().length != 1) {
var w_id = $(this.state.w_id_arr).not($("#selectWell").val()).get();
this.props.handleUnselect(w_id);
this.state.unselect = true;
}
}.bind(this));
},
This is the code for the dropdown menu where the selected item should be displayed when the browser reloads:
{/* drop-down field for well-name */}
<div className="row">
<div className="col-xs-12 col-md-12">
<TbHorizontalForm.Select2Group
id="selectWell"
onChange={this.handleWellChange}
multiple="multiple"
sel2-options={wellOpts}
defaultValue={[this.state.select_well]}
sel2-element='select' />
</div>
</div>