Nick McLean
Nick McLean

Reputation: 641

React props not loading fast enough

I am trying to useEffect to set the latitude and longitude of a map when a component loads. The problem is that the component loads and renders before the props are added to the useEffect.

useEffect(() => {
    console.log(props.bandLocation)
    // If I run this with a setTimeout it returns the data... but without the setTimeout it is an empty array. I need to set the latitude and longitude below to the data passed in through props... 
    setViewport({
        latitude: props.bandLocation[0],
        longitude: props.bandLocation[1],
        width: '100%',
        height: '200px',
        zoom: 2,
    })
}, [])

Upvotes: 2

Views: 1367

Answers (2)

Hadi Pawar
Hadi Pawar

Reputation: 1126

Set useEffect dependency to props so that when the props change the component re-renders accordingly. like this:

useEffect(() => {
    console.log(props.bandLocation)
    // If I run this with a setTimeout it returns the data... but without the setTimeout it is an empty array. I need to set the latitude and longitude below to the data passed in through props... 
    setViewport({
        latitude: props.bandLocation[0],
        longitude: props.bandLocation[1],
        width: '100%',
        height: '200px',
        zoom: 2,
    })
}, [props])

To further explain this the useEffect you currently have isn't aware of its surroundings so to say, as in it runs on component mount but then it doesn't care what happens. When you add props as a dependency, not only does it run the first time it also keeps a watch on changes to the props and then runs again whenever it detects changes.

Upvotes: 0

twharmon
twharmon

Reputation: 4282

Destructure props and add dependencies to the effect:

const { bandLocation } = props
useEffect(() => {
    setViewport({
        latitude: bandLocation[0],
        longitude: bandLocation[1],
        width: '100%',
        height: '200px',
        zoom: 2,
    })
}, [bandLocation])

This way, the effect will run only when bandLocation changes.

Upvotes: 2

Related Questions