react-native socket.io emit / on doesn't work

Multi tool use
react-native socket.io emit / on doesn't work
Hello guys I studying a simple chat app with RN
I checked connection with connection event at Server code Also server can get my socket's id
But, Any Emit or On doesn't work.
Here's my server Code
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
console.log("serverStarted");
var server = http.createServer(app);
const io = require('socket.io')(server);
server.listen(3000); //listen on port 80
io.on('connection',function(socket){
console.log("Client Connected."+socket.id);
socket.on('Button',function(data){
console.log("ButtonPressed");
});
socket.emit('userid',socket.id);
});
And this is Client side code
import React, { Component } from 'react';
import {
Button,
Alert,
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import SocketIOClient from 'socket.io-client';
let socket;
type Props = {};
export default class App extends Component<Props> {
constructor(){
super();
socket = SocketIOClient('http://myip:3000');
Alert.alert("Socket is Connected.");
socket.on('userid',(id)=>{
this.setState({userid:{id}});
Alert.alert(id);
})
}
state = {
userid:"id"
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Button title = "pres" onPress={()=>{
socket.emit('Button',"button");
}}>
</Button>
<Text style={styles.instructions}>
{this.state.userid}
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
With this code, When I press Button I think that the socket.on Works in Server
Also when socket is connected in server, the client change the Text in Render.
But both doesn't work.
Please help me...
this.setState({userid:{id}});
this.setState({userid:id});
{this.state.userid}
{this.state.userid.id}
Thank you for comment, But this one can't solve the problem socket.emit('Button',"button"); can't work
– inhoLee
Feb 27 at 16:28
2 Answers
2
I Found Problem.....
The Socket.io is updated so I need to replace
import io from 'socket.io-client'
to
import io from 'socket.io-client/dist/socket.io';
First of all goto you project root directory and install
npm i socket.io-client
import SocketIOClient from 'socket.io-client';
constructor(props) {
super(props);
//use your own local ip
this.socket = SocketIOClient('http://localhost:9000/');
this.socket.on('response', (messages) => {
Alert.alert("response." + JSON.stringify(messages));
console.log("response" + JSON.stringify(messages));
});
}
componentDidMount(){
this.socket.emit('Request_name', '1');
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
this.setState({userid:{id}});
should bethis.setState({userid:id});
or{this.state.userid}
should be{this.state.userid.id}
– bennygenel
Feb 27 at 7:59