Ad

ReactJS Socket.io Any Function Defined Or Called Under Socket On Gives Type Error Not A Function

- 1 answer

Im trying to get value from the server & update the client state. The value can be seen by console log. But whenever i call a function it shows error not a function. Here it shows "TypeError: this.setState is not a function"

client:

import React, { Component } from 'react';
import Navbar from './navbar.js';
import RemPage from './rempage.js';
import socketIOClient from "socket.io-client";

class App extends Component {
constructor(props){
super(props);
this.state = {
  i:'Ahoy',
  endpoint: "http://127.0.0.1:34001"
};
}

componentDidMount() {
const {endpoint} = this.state;
const socket = socketIOClient(this.state.endpoint);
socket.on('connect', function() {
  socket.on("outgoing data",data => this.setState({i: data.num}));
});

//console.log(data.num)

}
render() {
 const {response} = this.state;
return (
  <div>
  <p> {this.state.i} </p>
  </div>);
}
};
export default App;
Ad

Answer

use nextgen javascript arrow function:

componentDidMount() {
   const {endpoint} = this.state;
   const socket = socketIOClient(endpoint);
   socket.on('connect', () => {
     socket.on("outgoing data",data => this.setState({i: data.num}));
   });
}
Ad
source: stackoverflow.com
Ad