Reputation: 327
I'm a beginner to development and I'm getting Undefined is not an object error. What am I doing wrong here? When I console log placeID it returns value, but selectedPlace returns undefined. Thanks.
const PlaceDetailScreen = props => {
const [places, setPlaces] = useState([])
useEffect(() => {
const getPlaces = async () => {
const result = await axios.get('https://tgr-admin.appspot.com/api/places')
setPlaces(result.data)
}
getPlaces()
}, [])
const placeID = props.navigation.getParam('placeId')
const selectedPlace = places.find(place => place._id === placeID)
return (
<ScrollView>
<Image source={{ uri: selectedPlace.image }} style={styles.image} />
</ScrollView>
)
}
Upvotes: 0
Views: 1244
Reputation: 2614
The issue is with the selectedPlace, before getPlaces complete, the places is an empty array and .find method returns undefined. Accessing an image prop on selectedPlace undefined throws an error. Perform null check before accessing the image prop on selectedPlace.
const PlaceDetailScreen = props => {
const [places, setPlaces] = useState([])
useEffect(() => {
const getPlaces = async () => {
const result = await axios.get('https://#')
setPlaces(result.data)
}
getPlaces()
}, [])
const placeID = props.navigation.getParam('placeId')
const selectedPlace = places.find(place => place._id === placeID)
// selectedPlace is undefined and places equals []
// perform null check before accessing image prop
return (
<ScrollView>
<Image source={{ uri: selectedPlace && selectedPlace.image }} style={styles.image} />
</ScrollView>
)
}
Upvotes: 3
Reputation: 327
Based on Aadil Mehraj's answer, wrapping the content with null check also works. So I can add more stuff inside.
return (
<ScrollView>
{selectedPlace && (
<>
<Image source={{ uri: selectedPlace.image }} style={styles.image} />
<View style={styles.container}>
<MarkdownView styles={markdownStyles}>
{selectedPlace.content}
</MarkdownView>
</View>
</>
)}
</ScrollView>
)
}
Upvotes: 0