Answer the question
In order to leave comments, you need to log in
How to pass current user through socket io react?
data['nickname']; - current user here
//
const socket = io(':3000');
user = '';
socket.on('init', (data)=>{
user = data['nickname'];
});
class App extends React.Component {
....
}
componentWillMount() {
this.initSocket();
}
initSocket = () =>{
// set user
socket.on('init', (data)=>{
this.state.player = data['nickname'];
alert(this.state.player);
});
....
}
}
Answer the question
In order to leave comments, you need to log in
componentDidMount() {
this.initSocket();
}
initSocket() {
// set user
socket.on('init', data => {
this.setState({
player: data.nickname,
}, () => {
alert(this.state.player);
});
});
}
render() {
const { user } = this.state;
if (!user) return <Loader />
return (
...
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question