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
JavaScript
x
23
23
1
const mongoose = require('mongoose')
2
3
const animalSchema = new mongoose.Schema({
4
name: {
5
type: String,
6
required: [true, 'Please enter name'],
7
trim: true,
8
maxLength: [100, 'The name cannot exceed 100 characters']
9
},
10
11
image:
12
{
13
public_id: {
14
type: String,
15
required: true
16
},
17
url: {
18
type: String,
19
required: true
20
},
21
}
22
})
23
module.exports = mongoose.model('Animal', animalSchema);
AnimalReducer
JavaScript
1
27
27
1
export const animalDetailsReducer = (state = { animal: {} }, action) => {
2
switch(action.type) {
3
case ANIMALS_DETAILS_REQUEST:
4
return {
5
state,
6
loading: true,
7
}
8
case ANIMALS_DETAILS_SUCCESS:
9
return {
10
loading:false,
11
animal: action.payload,
12
13
}
14
case ANIMALS_DETAILS_FAIL:
15
return {
16
state,
17
error: action.payload
18
}
19
case CLEAR_ERRORS:
20
return {
21
state,
22
error: null
23
}
24
default:
25
return state;
26
}
27
}
and this is what i use on my frontend for showing the animal details
JavaScript
1
4
1
{animal.image && animal.image.map(img => (
2
<div key={img.public_id}>
3
<img className="d-block w-100" src={img.url} alt="" />
4
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.
JavaScript
1
5
1
> Object.prototype.map
2
undefined
3
> Array.prototype.map
4
[Function: map]
5
So you can remove the map and instead conditionally render the div:
JavaScript
1
3
1
{animal.image && <div key={img.public_id}><img className="d-block w-100" src={img.url} alt="" /></div>}
2
3