0

Hello I am trying to save in a state the response that my socket sends me through the back end

This is a method where I send messages to my socket

export default class Home extends Component { 

    constructor(){
        super()

        this.state = {
          informationReceived: 'Nothing yet!'
        }
        const token = localStorage.getItem('token');
        const socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
              informationReceived: receivedInfo
            })
          })

      }

      emitInfoToAll = () => {
        const token = localStorage.getItem('token');
        console.log('entrou')
        const socket = io('http://localhost:8080',{
            query: { token: token }
        });

        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
      }
}

But this way I would be opening connection to my socket twice when sending and receiving I was wondering how I can only open one connection so when I send a reply to my backend I don't have to open again

and how could I set these values ​​that I get for my p's tags:

                <p> Name: <span className = "name"> </span> </p>
                <p> Points: <span className = "points"> 0 </span> </p>

1 Answer 1

2

You should place socket as state of the component so that you can mock it in emitInfoToAll method

export default class Home extends Component { 

constructor(){
    super()

    this.state = {
      informationReceived: 'Nothing yet!'
      socket: null;
    }

    const token = localStorage.getItem('token');
    socket = io('http://localhost:8080', {
        query: { token: token }
    });

    socket.on('success', (receivedInfo) => {
        this.setState({
          informationReceived: receivedInfo
        })
      })

  }

  emitInfoToAll = () => {
    const { socket } = this.state;
    console.log('entrou')
    socket.emit('myevent', 'Hello realtime connected users!')
    console.log(this.state.informationReceived);
  }
}

Update: Help set value to p tag

export default class Home extends Component {

    constructor() {
        super()

        this.state = {
            informationReceived: 'Nothing yet!',
            socket: null
        }

        const token = localStorage.getItem('token');
        socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
                informationReceived: receivedInfo
            })
        })

    }

    emitInfoToAll = () => {
        const { socket } = this.state;
        console.log('entrou')
        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
    }

    render() {
        const { informationReceived } = this.state;
        const { name, point } = informationReceived;
        return (
            <div>
                <p> Name: <span className="name">{name}</span> </p>
                <p> Points: <span className="points">{point}</span> </p>
            </div>
        );
    }
}
Sign up to request clarification or add additional context in comments.

15 Comments

@gabriel I already update the new code that help you set the downloaded values to p's tag. Please check and mark it as correct if it work. Thanks
Why don't you use socket.on to listen which data changed in backend?
it is better to use useMemo But in my opinion better use context and place your socket client there, then you can useContext or consumer to access your socket client anywhere.
@VahidAlimohamadi yeap, your suggestion is better. But in that case I just help him bypass the problem as soon as possible
now you can place your socket events in componentDidMount if u use react-hooks it is equal to useEffect but with empty array as second arg.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.