'React not updating varibles

I'm trying to make a small webpage for a project. I use an esp32 to send a payload with MQTT. I want to show this message on a react app. but my postboxStatus doesn't update in my but if I console log it I can see that I updated it.

function Main() {

    var postboxStatus = "empty"

    const mqtt = require('mqtt')

    const host = 'test.mosquitto.org'
    const port = '1883'
    const clientId = `mqtt_${Math.random().toString(16).slice(3)}`
    
    const connectUrl = `mqtt://${host}:${port}`
    const client = mqtt.connect(connectUrl, {
      clientId,
      clean: true,
      connectTimeout: 4000,
      username: 'randomUserName',
      password: '',
      reconnectPeriod: 1000,
    })
    
    const topic = 'random/topic'
    client.on('connect', () => {
      console.log('Connected')
      client.subscribe([topic], () => {
        console.log(`Subscribe to topic '${topic}'`)
      })
      client.publish(topic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
        if (error) {
          console.error(error)
        }
      })
    })
    client.on('message', (topic, payload) => {
      console.log('Received Message:', topic, payload.toString())
      postboxStatus = payload.toString();
    })



  return (
    <div>
        <h1> {postboxStatus} </h1>
    </div>
  )
}

export default Main;




Solution 1:[1]

You cannot just change the variable and expect that React will re-render it. You should use useState() hooks for changing your state, like:

function Main() {
    const [postboxStatus, setPostboxStatus] = useState('empty');

    const mqtt = require('mqtt')

    const host = 'test.mosquitto.org'
    const port = '1883'
    const clientId = `mqtt_${Math.random().toString(16).slice(3)}`
    
    const connectUrl = `mqtt://${host}:${port}`
    const client = mqtt.connect(connectUrl, {
      clientId,
      clean: true,
      connectTimeout: 4000,
      username: 'randomUserName',
      password: '',
      reconnectPeriod: 1000,
    })
    
    const topic = 'random/topic'
    client.on('connect', () => {
      console.log('Connected')
      client.subscribe([topic], () => {
        console.log(`Subscribe to topic '${topic}'`)
      })
      client.publish(topic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
        if (error) {
          console.error(error)
        }
      })
    })
    client.on('message', (topic, payload) => {
      console.log('Received Message:', topic, payload.toString())
      setPostboxStatus(payload.toString());
    })



  return (
    <div>
        <h1> {postboxStatus} </h1>
    </div>
  )
}

export default Main;

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 Georgy