Skip to content
Advertisement

Error: animal.image.map is not a function

I am currently making a shelter web app using mern stack and i am struggling to display an image from my object. i already used the map but i think it is only for array objects. so i am clueless how to get the images.url on my animal object.

this is my animalSchema

const mongoose = require('mongoose')

const animalSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please enter name'],
        trim: true,
        maxLength: [100, 'The name cannot exceed 100 characters']
    },
    ...
    image: 
        {
            public_id: {
                type: String,
                required: true
            },
            url: {
                type: String,
                required: true
            },
        }
})
module.exports = mongoose.model('Animal', animalSchema);

AnimalReducer

export const animalDetailsReducer = (state = { animal: {} }, action) => {
    switch(action.type) {
        case ANIMALS_DETAILS_REQUEST:
        return {
            ...state,
            loading: true,
        }
        case ANIMALS_DETAILS_SUCCESS:
        return {
            loading:false,
            animal: action.payload,

        }
        case ANIMALS_DETAILS_FAIL:
        return {
            ...state,
            error: action.payload
        }
        case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }
        default:
        return state;
    }
}

and this is what i use on my frontend for showing the animal details

                            {animal.image && animal.image.map(img => (
                                    <div key={img.public_id}>
                                        <img className="d-block w-100" src={img.url} alt="" />
                               

Animal’s name, gender, breed and type are showing, only the animal.url is not.

Advertisement

Answer

It looks like your schema has animal.image defined as an object. Array.prototype.map only exists on arrays, not objects.

> Object.prototype.map
undefined
> Array.prototype.map
[Function: map]

So you can remove the map and instead conditionally render the div:

{animal.image && <div key={img.public_id}><img className="d-block w-100" src={img.url} alt="" /></div>}
                               
Advertisement