There is JSON called by fetch() request looks like this:
[{
"Info": "",
"Val": "3"
},
{
"Info": "",
"Val": "5"
},
{
"Info": "",
"Val": "1"
},
{
"Info": "",
"Val": "1"
}]
My purpose is to filter data according a filed called Val.
library = library.filter(item =>
item.Val==FilterVal
)
Let me make an example to explain what I want to do.
Look at this input :<input value={this.state.FilterVal} onChange={this.handlerFilter} />
FilterVal is going to be a number for example 1 or some numbers separated by comma 1,5,4 .
For example user types 1 on input ,the result must return the objects that Valis 1. For the next time type 1,5,4must return me the objects that Val are 1 and 5 and 4.
Here is a piece of my code:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
library: null,
FilterVal: "",
}
}
componentDidMount() {
fetch('/json.bc', {
method: 'POST',
})
.then(response => response.text())
.then(text => {
const Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
})
}
reorganiseLibrary = () => {
const { FilterVal} = this.state;
let library = data;
if (FilterVal !== "") {
library = library.filter(item =>
item.Val==FilterVal
)
}
library = _.chunk(library);
this.setState({
library
})
}
handlerFilter = evt =>
this.setState(
{
FilterVal: evt.target.value
},
() => {
this.reorganiseLibrary();
}
)
renderLibrary = () => {
const { library} = this.state;
if (!library || (library && library.length === 0)) {
return <div>nodata</div>
}
return library.map((item, i) => (
<div>
<span>{item.name}</span>
<span>{item.Val}</span>
</div>
))
}
render() {
const { library} = this.state;
return (
<div>
{this.renderLibrary()}
<input value={this.state.FilterVal} onChange={this.handlerFilter} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('Result'))
{this.state.FilterVal}. For exampleFilterVal = 1so result is objects ofJSONthat fieldValfor them is1,but I want whenFilterVal =1,2result will include objects ofJSONthat fieldValfor them are1and2.Does it make sense?