Data array initial value

Hi,

I have a UI-template node which values are contained in a data array as below.

data() {
   return{
        values:[]
     }
}

I want to initialize the values of this array with the data coming from msg.payload.
I tried using the mounted function with no success.
How would you do that ?

You can't initialise it with a value from msg.payload as it is initialised when the widget is loaded. You can update it when a message comes in by providing a watch msg function in the script. Something like

<script>
    export default{
        ...
        watch: {
            msg: function(){
                this.values = this.msg.payload
            }
        },
        ...

That assumes the values array is in msg.payload. Adjust according to where the values are. You might want to have some validation code to make sure the payload is valid before updating the data.

Hi Colin,

Awesome ! I have implemented your solution with minor adaptation to initialize the value only upon the first message received (using msgCount flag) and it answer my needs.

data() {
    return{
        values:[],
        msgCount:0
    }
},
...
watch: {
    msg: function(){
        if (this.msgCount==0) {
            this.values = this.msg.payload
            this.msgCount=1
        }
    }
},

Initialization of the array is also possible in mounted()

flows(22).json (3.7 KB)

In the flow you posted you have

<script>
    export default {
        data() {
            // define variables available component-wide
            // (in <template> and component functions)
            return {
                count: 0,
                data:[]
            }
        },
        ...
        mounted() {
            // code here when the component is first loaded
            this.data=[4,5,6];
        },
        ...

Is that any different to just doing

<script>
    export default {
        data() {
            // define variables available component-wide
            // (in <template> and component functions)
            return {
                count: 0,
                data:[4,5,6]
            }
        },

not different, I tried this first but it did not work, maybe I had another error in
the template.

your is definitely the better solution

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.