Reputation: 487
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?
Upvotes: 0
Views: 63
Reputation: 2032
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.
Upvotes: 1