0
votes

I just started using Cloudinary to upload picture in an application am working on. It is stored in MongoDB database as url link. I have succeeded with the upload. My database looks like this after saving:

id:5f90315331dc1727bc869afe
userEmail:"[email protected]"
image:"https://res.cloudinary.com/myapp/image/upload/v1603285331/ifyo38crk..."
imageId:"ifyo38crkdniixeimme9"
__v:0

My get() endpoint looks like this :

app.get("/getAvatar/:email", (req, res) => {
  userEmail= req.params.email;
  Image.find({userEmail:userEmail},(err, images)=> {
    if (err) {
      res.status(500);
      res.send(err);
    } else {
      res.json(images);
    }
  });
});

and my React front-end :

class AllImages extends Component {
    componentDidMount(){
        const{user}=this.props.auth
        const email = user.email
        this.props.getAvatar(email)
    }
    render() {
        return this.props.resumeData.map(image=>{
            return(
                <div className="image-card-container">
                    <div key={image.id} className='image-card'>
                        <h4>{image.userEmail}</h4>
                        <img
                        className='main-image'
                        src={image.image}
                        alt='profile image'
                        />

                    </div>


                </div>
            )

Redux action :

 export const getAvatar=(email)=>dispatch=>{
          
          dispatch(AvatarLoading());
          axios.post('/getAvatar/'+ email )
          .then(res=>
    dispatch({ 
      type:     GET_RESUME_AVATAR,
    payload: res.data
    
    })
    
    )
    history.push('/');
    };

On componentMount() i get the error :

TypeError: Cannot read property 'map' of undefined

something is definitely wrong with my code. This is my first time of working with Cloudinary, I will appreciate if anyone can help out!

1

1 Answers

0
votes

Add a null check inside render()

class AllImages extends Component {
    componentDidMount(){
        const{user}=this.props.auth
        const email = user.email
        this.props.getAvatar(email)
    }
    render() {
        return (
           <div>
            {this.props.resumeData && this.props.resumeData.map(image=>{
              return(
                <div className="image-card-container">
                    <div key={image.id} className='image-card'>
                        <h4>{image.userEmail}</h4>
                        <img
                        className='main-image'
                        src={image.image}
                        alt='profile image'
                        />
                    </div>
                </div>
              )}
           </div>
        )
    }

The render will get executed before componentDidMount and re-rendered on prop change.