Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native : state is getting undefined inside useCallBack hook function

State is getting undefined inside the useCallBack hook I think it is not getting scope to the state variable

const [selectedLocation, setSelectedLocation] = useState()
const selectLocationHandler = (event) => {
    setSelectedLocation({
        lat: event.nativeEvent.coordinate.latitude,
        lng: event.nativeEvent.coordinate.longitude
    })
    console.log('set location', selectedLocation)
}

const saveLocationPickerHandler = useCallback(() => {
    console.log('saveLocation', selectedLocation)
    if (!selectedLocation) {
        return;
    }
    props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [])

set location Iam getting Object { "lat": 37.775030512686214, "lng": -122.4273883345241, }

where as savelocation is undefined in console

like image 776
yaswanthkoneri Avatar asked Oct 17 '25 15:10

yaswanthkoneri


1 Answers

You need to provide selectedLocation as a dependency. Else the callback will not update if the state changes.

const saveLocationPickerHandler = useCallback(() => {
    console.log('saveLocation', selectedLocation)
    if (!selectedLocation) {
        return;
    }
    props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [selectedLocation])

If you provide an empty array as dependency the useCallback function will always have the initial state and never update (selectedLocation). This is the same behaviour useEffect has

like image 164
Tobias Lins Avatar answered Oct 20 '25 04:10

Tobias Lins