Aishwarya Chaturvedi
Aishwarya Chaturvedi

Reputation: 203

React component will mount is not getting called

I have been working on a chat application using react and websockets, My problem is the method

componetWillUnmount() doesn't get called when the state changes and component re-renders.

I have been trying to add 'li' elements to my chatArea component for every new message coming in a chat, and as soon as I am selecting another chat, I want to remove all those 'li' elements that were rendered in previous chat, for that I have tried 2 things, one to remove all child of or I am changing the state. But componentWillUnmount is not getting called. And i am not able to remove li elements.

Below is my code

import React from 'react'

export default class ChatArea extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      currentUser: this.props.currentUser,
      selectedUser: this.props.selectedUser,
      messages: []
    }
    this.handleMessage = this.handleMessage.bind(this)
  }

  handleMessage (obj) {
    let messages = this.state.messages
    messages.push(obj)
    this.setState({
      messages: messages
    })
  }

  componentWillMount () {
    window.socket.on('show message', obj => {
      this.handleMessage(obj)
    })
  }

  componentDidMount () {
    window.socket.emit('join', {
      sender: this.state.currentUser,
      receiver: this.state.selectedUser
    })
  }

  componentWillUnmount () {
    console.log('something')
    const chatList = this.refs.chatList
    while (chatList.hasChildNodes()) {
      console.log('removing children', chatList.lastChild)
      chatList.removeChild(chatList.lastChild)
    }
orrrrrrrrrrrrrr
      this.setState({
        messages: []
      })
  }

  render () {
    console.log('chatARea state', this.state)
    let messages = this.state.messages
    let i = 0
    return (
      <div className='row chat-area'>
        <ul className='col m12' ref='chatList'>
          {messages.map(msg => <li key={i++}>{msg.sentBy.firstname + ': ' + msg.message}</li>)}
        </ul>
      </div>
    )
  }
}

module.exports = ChatArea

Upvotes: 0

Views: 2722

Answers (1)

Aishwarya Chaturvedi
Aishwarya Chaturvedi

Reputation: 203

I found out the answer of my own question, the state of the component was not getting changed, so the method componentWillMount() was not getting called.

Thanks everyone for the help

Upvotes: 2

Related Questions