Reputation: 331
This is the JSON Input that I am going to filter by orderId and then set to the state variable.
[{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama,Wijerama,Srilanka","productName":"Apple","quantity":2,"total":100.0,"id":null,"order_date":"2019-01-31 10:28:29"}]
this is my state.
this.state = {
merchentOrders: [],
filterMerchentOrders: []
}
//this is the method
when I am filtering by orderId it's successfully working and then I want to set the filtered output to " this.setState({filterMerchentOrders: filterMerchentOrdersX});
". when I console out the state as below the values are not set.
getOrderDetails = id => {
console.log("id ==" ,id);
let filterMerchentOrdersX = this.state.merchentOrders.filter(value => {
return (
value.orderId.toString()
.indexOf(id) !== -1
);
});
this.setState({filterMerchentOrders: filterMerchentOrdersX});
//this is working
console.log("filterMerchentOrdersX ==" ,filterMerchentOrdersX);
//this gives an empty array
console.log("this.state.filterMerchentOrders ==" ,this.state.filterMerchentOrders);
};
Upvotes: 2
Views: 83
Reputation: 2300
It might be the reason that setState
runs asynchronusly, when you console.log
the value state might not be updated.
To view the state after it updates, you can pass a callback function.
this.setState({filterMerchentOrders: filterMerchentOrdersX},()=>{
console.log("this.state.filterMerchentOrders ==" ,this.state.filterMerchentOrders);
})
Upvotes: 1
Reputation: 678
Since you're using the ES6 syntax, your function could be shorter and neater. But it seems to me that you're not doing anything wrong
getOrderDetails = id => {
const filterMerchentOrders = this.state.merchentOrders.filter(
value => value.orderId.toString().indexOf(id) !== -1
);
this.setState({filterMerchentOrders});
}
Upvotes: 0
Reputation: 457
you've written console.log() immediately after setState method, since setState is an async method an at the time java script runs your console.log it will be showing you the previous state in which obviously array is not set, for this you should put your console in the second argument of setState that is a callback function.
this.setState({[event.target.name]: event.target.files[0]},()=>console.log(this.state));
or you can simply user async await.
Upvotes: 0