'How to filter the data from an API in a ethical way? Im using react JS
it work properly but I refresh the page i get this error "TypeError: Cannot read properties of undefined"
here is my code
for fetching the data from API
useEffect(() => {
let isSuscribe = true
axios.get(myLocalAPI)
.then(res =>
{
if (isSuscribe) {
setData(res.data)
}
}
)
.catch(err => console.log(err))
return () => isSuscribe = false
})
I have a 3 Combo box for filtering the data for Year,Month and Day. the date format on my API was this "YYYY-MM-DD"
When I filter the data of course it will show on DataGrid and also get the Total sales on within that date
to implement that this is my Code
For filter Table "Yvalue + "-" + Mvalue + "-" + Dvalue" = YYYY-MM-DD
const filter_table = () =>{
return Data.filter(
date=>date.Customer_date
.toLowerCase()
.includes(Yvalue + "-" + Mvalue + "-" + Dvalue) )
}
for filter and get the Total sales
const filter_data = () => {
return Data.filter(
date=>date.Customer_date
.toLowerCase()
.includes(Yvalue + "-" + Mvalue + "-" + Dvalue)) //Filter the data first
.map(e=>e.Customer_total) //When it true map the Total for each data
.reduce((a,b)=>a+b, 0 ) // Sum the total
}
when I Click the button and console both return funnction it work properly but when i implement this on DataGrid
<DataGrid
columns={columns}
getRowId={(rows) => rows.Customer_ID}
rows={filter_table()}
pageSize={10}
/>
<span className="featuredTitleperoBlack">{filter_data()} </span>
and I get this error Cannot read properties of undefined
can I ask you guys please explain why I get this error and ethical way to filter the data ?
I really appreciated if there is sample code so that I learn where I was wrong
Thank you!!!
Solution 1:[1]
When you've just refreshed the page, you don't have the data yet - the server did not respond yet - but you're already trying to filter it.
One way to solve is to check for Data to exist. Another way is conditional chaining, like this
Data?.filter(filterFunction) // if Data is present, it will be filtered
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PYTHON DEVELOPER999 |
