Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading "small')

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>
);

these is data that I needenter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

everything seems well but this is an error
enter image description here

>Solution :

!infor ? <img src={spinner} /> : /**/

In above line !infor will always be true as !{} is true.
There are 2 ways to solve your problem.

  1. initialize infor to null

    const [infor,setInfor] = useState(null);

  2. Use Object.keys() to validate object

    !Object.keys(infor).length ? <img src={spinner} /> : /***/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading