I have a problem concern filter in JavaScript can't working. I'm not sure may because API using long time for response
My code :
const getDataAll = () =>{
const [machines, setMachines] = useState([])
const getMc = async () =>{
try {
const resMc = await axios.get("My API")
setMachines(resMc.data)
} catch (err) {
console.error(err.message)
}
useEffect(()=>{
getMc()
},[])
const sumData = () =>{
const filterName = machines.data.filter((el) => el.name == "v10turbo")
}
}
Filter have show this alert in some time.
And i see time show in browser for API response around 8-9 second follow image below
I'm not sure if I got it right. if right please help me with to solve this problem
The code itself is correct. But when your component renders, there is no data yet, useeffect works after rerender. You need a loading state:
const getDataAll = () =>{ const [machines, setMachines] = useState([]); const [loading, setLoading] = useState(true); const getMc = async () =>{ try { const resMc = await axios.get("My API") setMachines(resMc.data) setLoading(false); } catch (err) { console.error(err.message) } finally { setLoading(false); } } useEffect(()=>{ getMc() },[]) const sumData = () =>{ const filterName = machines.data.filter((el) => item.name == "v10turbo") } } if(loading) { return<p>Loading...</p> }
This should fix it.