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
CodePudding user response:
!infor ? <img src={spinner} /> : /**/
In above line !infor
will always be true as !{}
is true.
There are 2 ways to solve your problem.
initialize
infor
tonull
const [infor,setInfor] = useState(null);
Use Object.keys() to validate object
!Object.keys(infor).length ? <img src={spinner} /> : /***/
CodePudding user response:
In the first render when your compiler is searching for the infor.image, it is getting undefined, thus it is throwing an error. Either use put checks for the same like checking for infor exist, then image exists and then small exist. It can be done by using infor?.image?.small. But the problem with this is that you will get undefined on the screen. You have to put the checks correctly by keeping this in mind for example infor?.image?.small ? infor.image.small : ''.