Charwisd
Charwisd

Reputation: 63

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
}

Upvotes: 1

Views: 2024

Answers (1)

Charwisd
Charwisd

Reputation: 63

That's was because of JavaScript's websocket.onmessage function use a copy of state, when it was assigned.

The solution is:

  • to make lastMessage as react useState
  • make websocket.onmessage function to setState of lastMessage
  • use useEffect to catch lastMessgae change

Upvotes: 4

Related Questions