Filter Json Data In React.js
I have this state defined: constructor(props){ super(props); this.state = { open: false, customers:[], customer:{},
Solution 1:
Make a new function getFavouriteProduct
that would looks something like this
getFavouriteProducts() {
fetch(all products)
.then((response1) => {
fetch(fav products)
.then((resonse2) => {
// filter response1 on the basis of response2this.setState({desiredState: desiredOutput})
})
})
}
edit: You can to do this from a single function as well.
getEverything() {
fetch(data_by_get_product)
.then((response1) => {
fetch(data_by_get_customer)
.then((resonse2) => {
// filter response1 on the basis of response2this.setState({states_changed_by_getProduct: response1})
this.setState({states_changed_by_get_customer: response2})
this.setState({desiredOutput: filteredOutput}}
})
})
}
Solution 2:
You should use filter & map:
isProductInFavorites(product) {
// TODO: Return true if the current product is in the Customer's favorites
}
render() {
const products = this.state.products
.filter((product) =>this.isProductInFavorites(product))
.map((product) => [product.name, product.price])
return (
<DataTablesheight={'auto'}
selectable={false}showRowHover={true}columns={FAV_TABLE_COLUMNS}data={products}showCheckboxes={false}rowSizeLabel="Filas por página" />
)
}
I'm not sure if you need an array of data or an object, but if you need an object, the function should be (product) => {name: product.name, price: product.price}
.
Also, I'd like to make sure you know that fetch need you to check the status of the response, like described in the Github Polyfill. And it might be better if the server managed a "favorite" status on each product before returning the list for getProducts
.
Post a Comment for "Filter Json Data In React.js"