V
V
Vladimir2022-04-01 10:53:02
React Native
Vladimir, 2022-04-01 10:53:02

Is the state already reset when unmounting a component in React Native?

I am writing a small mobile application (I have never done this before, so I apologize for the stupidity), which should track the user's coordinates while working. Accordingly, I subscribe to watchPositionAsync and want to unsubscribe when exiting the screen. The code is something like this (almost everywhere there are console.log stubs to understand what is happening):

function SurveyScreen({ route, navigation }) {
  ...
  const [passengers, setPassengers] = useState(0)
  const [location, setLocation] = useState(null)
  ...
  const locCallback = (locationObject) => {
    console.log(locationObject.coords)
  }

  useEffect(() => {
    if (locSub == null) {
      (async () => {
        setLocSub(await Location.watchPositionAsync({ accuracy: Location.Accuracy.Highest, timeInterval: 5000 }, locCallback))
      })()
    }
    return () => {
      console.log(`!! ${locSub}`)
      if (locSub !== null) {
        console.log(`locSub is: ${locSub}`)
        console.log(`locSub.remove is: ${locSub.remove}`)
        locSub.remove()
      }
    }
  }, [])

  useEffect(() => {
      ...
      console.log(locSub)
      ...
    }
  }, [passengers])
...


The subscription goes well, the coordinates in locCallback go, but when the component is unmounted (I leave through navigation), then locSub is already null. In the console it looks like this:
Object {
  "remove": [Function remove],
}
Object {
  "remove": [Function remove],
}
Object {
  "remove": [Function remove],
}
Object {
  "remove": [Function remove],
}
!! null


While the component is active, the main UseEffect perfectly sees the saved locSub, but at the cleanup stage it is already null. What could be the problem? I read in all the manuals that the cleanup function is written precisely in order to unsubscribe from all subscriptions, etc. But it turns out that at the time of its call, the state is no longer available?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question