'React state not updating inside Websocket.onmessage
While I'm trying change state in onmessage function. State changes only on moment of render, after that state value become 'undefined' again. Why does react change the state in moment of render and then drop it?
export default function Connector () {
this.protocol = 'http://'
this.wsprotocol = 'ws://'
this.server = '127.0.0.1:8000';
[this.currentFolder, this.changeFolder] = useState();
this.urls = {
auth: this.protocol+this.server+'/user/login',
get_file: this.protocol+this.server+'/file',
create_folder: this.protocol+this.server+'/create/repository',
send_file: this.protocol+this.server+'/load-file',
ws: this.wsprotocol+this.server+'/ws'
};
[this.websocket, ] = useState(new WebSocket(this.urls.ws));
const onMessage = (data: MessageEvent) => {
const message = JSON.parse(data.data)
switch(message.title) {
case 'file': {
if (message.status === 'ok') {
console.log('got file, ID: '+message.file.ID)
if (message.file.is_folder) {
this.changeFolder(message.file)
}
} else {
console.log(message.message)
}
break
}
}
};
useEffect(() => {
this.websocket.onmessage = onMessage;
this.websocket.send(JSON.stringify({title: 'get file', ID: 1}))
}, [])
useEffect(() => {
console.log(this.currentFolder) // here is ok on a moment of render after calling changeFolder()
}, [this.currentFolder])
useEffect(()=>{setInterval(()=>console.log('main:', this.currentFolder), 1000)}, []) // always undefined
}
Solution 1:[1]
You cannot use React Hooks within class components.
Although you are not using the class keyword, it seems to me that you're under the impression that Connector is a class based on your usage of the this keyword.
Please read the React docs carefully with the above in mind, and learn the differences between class and function components.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raphael Rafatpanah |
