'filter is not setting state as intended, how do i create async if statement?
I'm fetching data from my backend and storing it as a state. Inputs from local storage are then supposed to be filtering the backend data and rendering the results. However it seems my .filter isn't setting state as anything (undefined). However, if i save my code after a duration of time it then operates as intended until i refresh.
What is happening, do i need to create a async statement?
import "./Home.css";
import axios from 'axios';
const Tables = () => {
const [data, setData] = useState();
const [isloading, setIsLoading] = useState(true);
const [result, setResult] = useState();
const test = async () => {
await axios.get('http://localhost:5000/').then((res)=>{
setData(res.data.data)
setIsLoading(false)
})
const storedSize = localStorage.getItem('size');
const storedFeel = localStorage.getItem('feel');
const storedCost = localStorage.getItem('cost');
const storedStyle = localStorage.getItem('style');
const storedRoom = localStorage.getItem('room');
const info = {size: storedSize, feel: storedFeel, cost: storedCost, style: storedStyle, room: storedRoom};
const keys = Object.keys(info);
const values = Object.values(info);
const x = values;
const type = keys;
if(type[3]==="style") {
const filterProcess = data?.filter( i => {
return i.style===x[3];
})
setResult(filterProcess)
};
};
useEffect(() => {
test();
}, []);
if (isloading){
return <h2>Loading...</h2>
};
const clear = () => {
window.location = '/First';
localStorage.clear();
};
const renderTable = () => {
return result?.map((hero)=>{
return (
<div className="card mx-2" style={{width: '18rem'}} key={hero.data_id}>
<img className="card-img-top" src={hero.image} alt="Card image cap"/>
<div className="card-body">
<h5 className="card-title">{hero.name}</h5>
<p className="card-text">Feel: {hero.feel}</p>
<p className="card-text">Style: {hero.style}</p>
<p className="card-text">Cost: £{hero.cost}</p>
<p className="card-text">Room: {hero.room}</p>
<p className="card-text">Size: {hero.size}</p>
<a href={hero.web_link} target="_blank" className="btn btn-primary">Go to link</a>
<br/>
</div>
</div>
)
})
};
return (
<Fragment>
{renderTable()}
<button className="btn btn-primary" onClick={clear}>New Search</button>
</Fragment>
);
};
export default Tables;```
Solution 1:[1]
Resolved! - I moved my data state inside the useEffect dependencies.
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 | Oran_Cowell |
