Home > OS >  Data in template seems not reactive after updates in Pinia store state
Data in template seems not reactive after updates in Pinia store state

Time:01-09

When i create a widget, and then update aWidget. The select must appear, but seems that aWidget did not get updated. error only occurs when the initial state of aWidgets is empty array template:

<select  v-if="bShowWidgetSelect" v-model="iSelectedWidgetNoOption">
    <option v-for="(aWidget, iWidgetNo) in aWidgets" @click="switchSelectedWidget(iWidgetNo)" :value="iWidgetNo">{{ aWidget.widget_name }}</option>
</select>

pinia state:

state: () => {
    return {
        aWidgets: [],
        aSelectedWidgetData: [],
        aWidgetNumbers: [],
        iWidgetCount: 0,
        iSelectedWidgetNo: 0,
        iMaxCreateWidget: 0
    }
},

pinia action:

async createWidget(oParams) {
        let oStore = this;
        await oWidgetRequests.createWidgetRequest(oParams)
            .then(function (oResponse) {
                let oCreatedWidget = oResponse.data.data.widget;
                let iWidgetNo = oCreatedWidget.widget_no;
                oStore.aWidgets[iWidgetNo] = oCreatedWidget;
                oStore.iSelectedWidgetNo = iWidgetNo;
                oStore.iWidgetCount = oStore.iWidgetCount   1;
            })
            .catch(oError => {
                alert('Error\n'   oError.response.data.error.message_key);
            });
    }

CodePudding user response:

You are naming two variables with the same name: v-for="(aWidget, iWidgetNo) in aWidget".

Try to use a different name for the inner loop variable: v-for="(myWidget, iWidgetNo) in aWidget"

CodePudding user response:

I changed the way of updating the aWidgets data if it were initially empty

/**
     * Request to create widget
     * @param oParams
     */
    async createWidget(oParams) {
        let oStore = this;
        await oWidgetRequests.createWidgetRequest(oParams)
            .then(function (oResponse) {
                let oCreatedWidget = oResponse.data.data.widget;
                let iWidgetNo = oCreatedWidget.widget_no;
                if (oStore.iWidgetCount === 0) {
                    oStore.aWidgets = {[iWidgetNo]: oCreatedWidget};
                } else {
                    oStore.aWidgets[iWidgetNo] = oCreatedWidget;
                }
                oStore.iSelectedWidgetNo = iWidgetNo;
                oStore.iWidgetCount  ;
            })
            .catch(oError => {
                alert('Error\n'   oError.response.data.error.message_key);
            });
    }
  • Related