0

I'm making a chat app and want to keep its parts separate.

For example, I have part of code where communication logic is described. So when somebody receives a message addMessage function can be used to pass it to react component:

import { addMessage } from './components/App.Chat.MessageField'

rtc.on('data', (data) => {
  /.../
  addMessage(message);
});

And addMessaget function is binded method of react component:

export var addMessage;

export default class MessageField extends Component {

  constructor() {
    /.../
    addMessage = this.addMessage.bind(this);
  }

  render() {
    /.../
  }

  addMessage(message) {
    /.../
    this.setState(/.../);
  }

}

So far, everything worked well. But I doubt that's good solution. Can it cause some problems or is there any better ways to do it?

3
  • 1
    Component methods are generally only supposed to be used by the component itself or possibly passed as props to child components. They should not be regarded as a public API. You could instead create a rtc.on listener in componentDidMount of the component, and remove the listener in componentWillUnmount. Commented Nov 9, 2018 at 10:27
  • @Tholle, thanks I'll try it. But I don't understand is this a bad practice only because of readability and conventions, or it can cause real mistakes in work of react app. Commented Nov 9, 2018 at 10:38
  • I don't think it will work, since each instance of the MessageField class will have a addMessage method bound to itself, so it's not clear which component's addMessage you will invoke by doing it like that. Commented Nov 9, 2018 at 10:49

1 Answer 1

1

This will lead to bugs. If you invoke setState on an unmounted component React will throw an error. In your example it means that if you are not in the case where MessageField is never unmounted then at some point addMessage will throw. Of course your app should not rely on any of your component never unmounting as it is a core part of the react's semantics.

A better way to do this could be to use redux and have the "add message" behaviour refactored around using redux state and actions. Your rpc.on snippet could be also put inside its own middleware.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.