1

I am using react native hooks to pass data from my main screen to a secondary screen however some of the data I get back will be null.

const { profileData } = navigation.state.params;

Which results in a error like this: "Uncaught TypeError: Cannot read property 'stage' of null"

Which is coming from this useEffect on my secondary screen:

 useEffect(() => {
        if(profileData.item.levelrequest.stage == "Submitted") {
            setlrequest05(true)
        } else if(profileData.item.levelrequest.stage == "") {
            setlrequest05(false)
        } else if(profileData.item.levelrequest.stage == "Approved") {
            setlrequest05(false)
        }
    })

How can I allow it to not care that the stage field is null for some users?

Robert
  • 343
  • 6
  • 16

1 Answers1

0

"Cannot read property 'stage' of null" is actually telling you that levelRequest is null. This can certainly mean that any one of the parents of stage is null...and there isn't any magic way in JS to get around actually checking each level of the object to make sure it exists.

You can either tighten up your schema on your server by making those fields required, but the most straightforward way to handle this would be to write a 'guard' conditional at the beginning of your function, like this:

useEffect(() => {
  if (!profileData ||
      !profileData.item || 
      !profileData.item.levelRequest ||
      !profileData.item.levelRequest.stage) {
    // do something to handle null data...probably `return` so the other 
    // conditional of the hook isn't fired
  }
  ...rest of your function here...
})

This is a crude example, but it expresses the idea. This situation is discussed with more expertise and detail in this thread.

David Miner
  • 198
  • 2
  • 10