Answer the question
In order to leave comments, you need to log in
How to update data in componentDidMount if data comes from socket?
I plan to update the data somehow
componentDidMount() {
this.setState({
data: вот сюда надо както доставить новые данные
});
}
const ws = new WebSocket("ws://api...");
ws.onmessage = responce => console.log(responce.data);
Answer the question
In order to leave comments, you need to log in
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();
}
}
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();
}, []);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question