Home > database >  Data render before server call in reactjs
Data render before server call in reactjs

Time:03-17

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

CodePudding user response:

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 || {})
  • Related