I am following a tutorial and just learned about useEffect
.
The issue I am having is that I want to get result.hours[0].is_open_now
. I've discovered that the component renders twice, and since hours is undefined at first, it fails.
Is there a way to make this only run once.
const ResultsShowScreen = ({ navigation }) => {
const id = navigation.getParam('id');
const [result, setResult] = React.useState({})
const getResult = async (id) => {
const response = await yelp.get(`/${id}`)
setResult(response.data)
}
useEffect(() => {
getResult(id)
}, [])
if (!result || result.length <= 0) {
return null
}
const {name,
display_address,
price,
display_phone,
photos,
review_count,
rating,
hours
} = result
if (hours && hours.length > 0 ) {
const is_open_now = hours[0].is_open_now
console.log('running')
} else {
console.log('nooooo')
}
return (
<View>
<Text style={styles.title}>{name}</Text>
<Text>Price: {price}</Text>
<Text>Rating: {rating}</Text>
<Text>Reviews: {review_count}</Text>
<Text>Phone: {display_phone}</Text>
<Text>Is Open Now: </Text>
</View>
)
}
export default ResultsShowScreen