S
S
semki0962020-02-18 17:05:47
React
semki096, 2020-02-18 17:05:47

How to update data in componentDidMount if data comes from socket?

I plan to update the data somehow

componentDidMount() {
      this.setState({
        data: вот сюда надо както доставить новые данные
      });
    }

And I receive new data from the socket like this
const ws = new WebSocket("ws://api...");
ws.onmessage = responce => console.log(responce.data);

That is, I need to somehow take the last message from the socket and add it to this.state.data and do it right. Moreover, the data must be updated on the onmessage event (but that's another question). I will be grateful for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2020-02-18
@semki096

Like this:

class WS extends React.Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] };
    this.ws = new WebSocket("ws://api...");
  }

  componentDidMount() {
    this.ws.onmessage = responce => this.setState({ ...this.state, messages: [ ...this.state.messages, responce.data ] });
  }

  componentWillUnmount() {
    this.ws.close();
  }
}

or on hooks
import React, { useEffect, useState } from 'react';

function ws() {
  const [message, setMessages] = useState([]);

  useEffect(() => {
    const ws = new WebSocket("ws://api...");
    ws.onmessage = responce => this.setState({ ...this.state, messages: [ ...this.state.messages, responce.data ] });
    return () => ws.close();
  }, []);
}

As you can see, on hooks, the logic is not spread over the entire component, but is located in one place.
Better yet, wrap it all in a React Context and subscribe to it in the right components via useContext (or Consumers). Then it is fashionable to save the message queue with all the necessary meta-data (for example, the time of receipt).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question