in my react project I get api and store data in state.
const [infor,setInfor] = useState({}); //these is my hook for store data
const [chartdata,setChartdata] = useState([]);
useEffect(()=>{
const setter = async()=>{
const dd = await(info());
setInfor(dd.data);
console.log(dd.data);
const dd2 = await(chart());
setChartdata(dd2);
}
setter();
},[])
It works properly and store data very well. I store data in (infor)
I want to use that data in react component so write these code
return (
<div id={style.main}>
{
!infor ? <img src={spinner} /> : //these code checking infor isn't null
<span className={style.info}>
<img src={infor.image.small} title={infor.id} className={style.icon} />
<p>{infor.market_cap_rank}</p>
<p>{infor.name}</p>
</span>
}
</div>
);
everything seems well but this is an error

>Solution :
!infor ? <img src={spinner} /> : /**/
In above line !infor will always be true as !{} is true.
There are 2 ways to solve your problem.
-
initialize
infortonullconst [infor,setInfor] = useState(null); -
Use Object.keys() to validate object
!Object.keys(infor).length ? <img src={spinner} /> : /***/
