Reputation: 95
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
Upvotes: 0
Views: 278
Reputation: 2931
Following your code you can not prevent useEffect
render twice because following react hook lifecycle,
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
That's mean useEffect
will be executed after component render the first time (Your code fiirst time is null) and executed more time if the second arg has values.
In your useEffect
, you call setState
to set new state and component auto render if state change. So your component will be rendered at least twice.
Upvotes: 3