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

Data render before server call in reactjs

All the times cannot read the property of undefined (reading ‘image’)

also i can see api does not call if i remove everything from return it does work well it does call useEffect but after return it does not call what is causing issue please guide

    const { id } = useParams();
    const dispatch = useDispatch()
    let user = useSelector(store => store.userById.data)

    useEffect(() => {
        console.log("******UseEffect***");
        dispatch(action.userById(id))
    }, [id]);

 return (
        <section id="rentalDetails">
         <img src={user.image} alt={user.title} />
       </section>
)

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

>Solution :

Be defensive and do not render the user related data if there is no user yet.

 return (
        <section id="rentalDetails">
         {user && <img src={user.image} alt={user.title} />}
       </section>
 )

Or provide a default object to the user until the api returns.

const user = useSelector(store => store.userById.data || {})
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