A
A
Alexander Ivanov2018-01-27 15:40:50
Node.js
Alexander Ivanov, 2018-01-27 15:40:50

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 {
....
}

The problem is that the react is loaded first and the user is added at the end
tried it through componentWillMount
componentWillMount() {
        this.initSocket();
    }

    initSocket = () =>{

        // set user
        socket.on('init', (data)=>{
            this.state.player = data['nickname'];
            alert(this.state.player);
        });
....
    }
}

but on boot it is still not detected.
How to extract the User from the node so that it can be passed to the React component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-01-27
@cimonlebedev

componentDidMount() {
  this.initSocket();
}

initSocket() {

  // set user
  socket.on('init', data => {
    this.setState({
      player: data.nickname,
    }, () => {
      alert(this.state.player);
    });
  });
}

1. Use componentDidMount instead of componentWillMount .
2. Never change the state directly, there is an asynchronous setState method for this . Otherwise, your component will not update.
3. This logic is best moved out of the component in redux-saga or redux-thunk .
4. In the component itself, you have not yet received the user, show the loader:
render() {
  const { user } = this.state;
  
  if (!user) return <Loader />  
  
  return (
   ...
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question