I am trying to write a shopping cart app which when we enter a value in search bar it should update the list and show item available based on value entered. With the code I wrote, everything is working fine until I made a selection of an item which is not updating the view at first time and showing all the channels.(I think state not updating at first time, but doing at second time)
I am pretty new to react. I tried to add only necessary code here for solution.
state = { open: false, value: '', filteredSections: 'none', displaySections: [] };
filterFunction(e, someSections) {
const filteredSections = [];
this.setState({ value: e.target.value });
someSections.forEach((category) => {
const results = [];
const itemCopy = {...category};
category.arraysinside.forEach((item) => {
if (item.name.toLowerCase().includes(e.target.value.toLowerCase())) { results.push(item); }
});
itemCopy.arraysinside = results;
if (itemCopy.arraysinside.length > 0) { filteredSections.push(itemCopy); }
});
this.setState({ filteredSections: filteredSections });
return filteredSections;
}
updateFunction(displaySections) {
this.setState({ displaySections: displaySections });
}
onChange(opt) {
// makes item selected and changes color of item to know that item is selected
}
render() {
const someSections = customization.arraysinside.filter(c => c.has === 'channels');
let { displaySections, filteredSections } = this.state;
return (
<div>
<FormControl
name="search-items"
placeholder="Search items"
onChange={(e) => {
filteredSections = this.filterFunction(e, someSections);
this.setState({
displaySections: filteredSections.length > 0 ? displaySections = filteredSections : 'No',
value: this.state.value,
});
}}
/>
<div>
{displaySections.length > 0 ? displaySections.map(section =>
<someSections
onChange={(opt) => {
onChange(opt);
this.updateFunction(opt, displaySections);
}}
:
someSections.map(section =>
<someSections
onChange={opt => onChange(opt)}
/>)
}
</div>
</div>
);
}
}
JSON FORMAT WILL BE
{
"name": "product 1",
"has": "channels",
"arraysinside": [
{ "selected": false, "name": "Item 1"},
{ "selected": false, "name": "Item 2"},
{ "selected": false, "name": "Item 3"},
{ "selected": false, "name": "Item 4"},
],
},
{
"name": "product 2",
"has": "channels",
"arraysinside": [
{ "selected": false, "name": "Item 1"},
{ "selected": false, "name": "Item 2"},
{ "selected": false, "name": "Item 3"},
{ "selected": false, "name": "Item 4"},
],
},
displaySections should be updated every time I select the item and should change the view instantly, but with current code, It updates when I enter another value or update selection next time. PLease help, I been trying it for days with no improvement. I will be glad, If suggested a easier way than I wrote.
setState()
is asynchronous, so try:
this.setState({ value: e.target.value }, () => { ... do stuff relying on value })
;