Search code examples
javascriptreactjsecmascript-6pusherisomorphic-javascript

TypeError: Cannot read property of undefined with web-sockets


Using Isomorphic framework for React and pusher to get websockets.

I can't seem to access state when I am in the componentDidMount() function.

class TopbarNotification extends Component {
   state = {
     visible: false,
     notifications: []
   };

  constructor(props) {
    super(props);
    this.state = {
     notifications: [],
     visible: false
    };
  }

  componentDidMount() {
    var pusher = new Pusher('xxxxxxxxxxxx', {
       cluster: 'xxx',
       encrypted: true
    });

    var channel = pusher.subscribe('notifications');
    channel.bind('new-notification', function (data) {
      let newNotifications = this.state.notifications.push(data)
      this.setState({
        notifications: newNotifications
      })
      alert(data.message);
    });

  }

  render() {
     // ...Blah blah, blah blah
  }
}

I am getting this error: TypeError: Cannot read property 'notifications' of undefined

Referring to this line: let newNotifications = this.state.notifications.push(data)

Why can I not access state inside componentDidMount()?


Solution

  • The function given to the channel.bind is overshadowing the this of componentDidMount(). Using an arrow function instead should do the trick.

    channel.bind('new-notification', data => {
      let newNotifications = this.state.notifications.push(data)
      this.setState({
        notifications: newNotifications
      })
      alert(data.message);
    });