I have an if statement in my code, that checks if the displayName is null. If it is then it retries, as the user has to wait for a firebase function to create the user data, which then gets changed by the user. The render has to return a loading screen while the displayName gets changed from null. My only problem is that when I check if the displayName is null, I get the error:
null is not an object (evaluating this.props.currentUser.displayName
Here is my code:
class MainPage extends Component {
constructor(props) {
super(props)
this.state = {
userDataFetched: false
}
this.checkUser = this.checkUser.bind(this)
}
componentDidMount() {
this.checkUser()
}
checkUser() {
if (this.props.currentUser.displayName !== null) {
this.userDataFetched = true
window.clearTimeout(this.checkUser)
console.log("Ran checkUser(), displayName=", this.props.currentUser.displayName, ", userDataFetched=", this.userDataFetched)
} else {
window.clearTimeout(this.checkUser)
window.setTimeout(this.checkUser, 500)
console.log("Retrying checkUser(), displayName=", this.props.currentUser.displayName)
}
}
render() {
if (this.userDataFetched) {
return
} else {
return (
<View>
<Text>Loading...</Text>
</View>
)
}
}
}
Is there a way to check the displayName without getting the error?
You're trying to read a property of null here:
if (this.props.currentUser.displayName !== null) {
You're probably passing null when a user isn't logged in, so you'll have to handle this case in your if statement.
if (this.props.currentUser && this.props.currentUser.displayName !== null) {
// Your logic
}
Above will ensure that currentUser is not null, so you can safely check whether the displayName property is set or not.