Search code examples
reactjsfirebasesetstate

Cannot read property of null - react.js state


I'm trying to make a todo list app with React and Firebase.

It's a single page app (except for login). In my Page's component, I call to a List's component. In my List's component, I get my firebase data that I put in a state. In React Dev Tool, in my List's component, I can see a state like this :

list{items{...},listName:"exemple"}

So, in my return, I'm trying to show the listName's value like that: {this.state.list.listName} But I have the following error: : Cannot read property 'listName' of null

This is my List's component :

  class ListPage extends Component {
      constructor(props) {
    super(props);

    this.state = {
      list: null,
    };
      }
      componentDidMount() {
    this.listRef = db.ref(`users/${this.props.user.uid}/lists
    ${this.props.cle}`);
    this.listRef.on('value', data=>{
        this.setState({
            list: data.val()
        })
    })
    }
     render() {
    return (
      <div>
        <h1>List : {this.state.list.listName}</h1>
      </div>
    );
  }
}

Where I am wrong ?

Thanks


Solution

  • The reason is because when your component first mounts, the state list is null. Only when the asynchronous firebase response comes back is it loaded with data and becomes non-null. The solution is to check if it's null, so in your render() function change this part:

    <h1>List : {this.state.list.listName}</h1>
    

    to this:

    { this.state.list && <h1>List : {this.state.list.listName}</h1> }
    

    In general it's good to check if objects are defined before accessing their properties. Especially ones you've explicitly defined to be null at some point.