Having trouble updating Vuejs array with new values

Currently, I am facing an issue with the template code for my survey builder. I am successfully receiving responses from the server, but the addAnotherQuestion value is not updating as expected. Despite trying various approaches, I have been unable to resolve this issue. Any assistance in resolving this problem would be greatly appreciated.

   <div v-for="(addItem, addItemIndex) in addAnotherQuestion" :key="addItemIndex">
     {{addItem.question}}
     {{addItem.options}}
   </div>

This is the default value set:

data() {
    return {
       addAnotherQuestion: [
        {
          id: 1,
          enableSingle: false,
          enableMultiple: false,
          enableLong: false,
          enableScale: false,
          enableMatrix: false,
          enableMatrixMulti: false,
          enablePlain: false,
          type: "single",
          // options: ["", ""],
          question_number: 1,
          disableOption: true,
          question: "",
          required: true,
          hasOther: false,
          isOpen: false,
          scale: '0',
          rows: [
            {
              label : "ROW 1",
              id : 1
            },
            {
              label : "ROW 2",
              id : 2
            },
          ],
          columns: [
            {
              label : "COL 1",
              id : 1
            },
            {
              label : "COL 2",
              id : 2
            },
          ],
        },
      ],
    }
mounted(){
this.getSurveyQuestion();
}
computed:{ ...mapGettersSurvey(["questionList"])},
methods:{
...mapActionsSurvey(["GET_SURVEY_QUESTION"]),
getSurveyQuestion() {
      let params = { id: this.surveyId };
      let isDetailsFound=false;
      this.GET_SURVEY_QUESTION(params).then((result) => {
        console.log('result', result)
        if (result) {
          //this is just a response from server not a code
          [
            {
            "id": 1,
            "question": "Test question -1",
            "question_number": 1,
            "options": [
                   "Option 1",
                   "Option 2",
                   "Option 3"
                      ],
             "required": true,
             "hasOther": false,
             "type": "single"
             },
             {
             "id": 2,
             "question": "Test Question -2",
             "question_number": 2,
             "options": [
                   "Option -1",
                   "Option -2"
              ],
              "required": true,
              "hasOther": false,
              "type": "multiple_choice"
              }
              ]
          //response over--this response is from server
          let details = this.questionList;
          if (details.length > 0) {
            isDetailsFound = true;
            for (let i = 0; i < details.length; i++) {
              if (details[i].type === "single") {
                details[i].enableSingle = true;
              } else if (details[i].type === "multiple_choice") {
                details[i].enableMultiple = true;
              } else if (details[i].type === "open_text") {
                details[i].enableLong = true;
              } else if (details[i].type === "distribution_scale") {
                details[i].enableScale = true;
              } else if (details[i].type === "single_variant") {
                details[i].enableMatrix = true;
              } else if (details[i].type === "multiple_variant") {
                details[i].enableMatrixMulti = true;
              } else if (details[i].type === "plain_text_number") {
                details[i].enablePlain = true;                
              }
            }

            this.addAnotherQuestion = details;
          }
        }
        if(!isDetailsFound){
          this.addAnotherQuestion[0].enableSingle = true;
        }
      });
    }
}

The issue lies with the options which are not updating correctly. https://i.sstatic.net/kCVnc.png

I have attempted the following approach:

if (details.length > 0) {                       
            let temp = this.addAnotherQuestion[0];
            let addAnotherQuestion2 = [];   
            console.log('addQ',this.addAnotherQuestion);
            isDetailsFound = true;
            for (let i = 0; i < details.length; i++) {
              let resultQuestion = temp; 
              console.log('temp',temp);             
              if (details[i].type === "single") {
                resultQuestion.id = details[i].id;
                resultQuestion.question_number = details[i].question_number
                resultQuestion.enableSingle = true;
                console.log(details[i].question);
                resultQuestion.question = details[i].question;
                resultQuestion.options = details[i].options;
                resultQuestion.type = details[i].type;
                resultQuestion.enableMultiple = false;
                resultQuestion.enableLong = false;
                resultQuestion.enableScale = false;
                resultQuestion.enableMatrix = false;
                resultQuestion.enableMatrixMulti = false;
                resultQuestion.enablePlain = false;   
                resultQuestion.disableOption = true,          
                resultQuestion.required = details[i].required;
                resultQuestion.hasOther = details[i].hasOther;                
                resultQuestion.isOpen = false;
                addAnotherQuestion2.push(resultQuestion);     
              } else if (details[i].type === "multiple_choice") { 
                resultQuestion.id = details[i].id;
                resultQuestion.question_number = details[i].question_number
                resultQuestion.enableSingle = false;
                resultQuestion.question = details[i].question;
                console.log(details[i].question);
                resultQuestion.options = details[i].options;
                resultQuestion.type = details[i].type;
                resultQuestion.enableMultiple = true;
                resultQuestion.enableLong = false;
                resultQuestion.enableScale = false;
                resultQuestion.enableMatrix = false;
                resultQuestion.enableMatrixMulti = false;
                resultQuestion.enablePlain = false;   
                resultQuestion.disableOption = true,          
                resultQuestion.required = details[i].required;
                resultQuestion.hasOther = details[i].hasOther;                
                resultQuestion.isOpen = false;  
                addAnotherQuestion2.push(resultQuestion);                                  
              }
             this.addAnotherQuestion.push(addAnotherQuestion2);

Answer №1

Your current code does not seem to utilize the result variable returned from this.GET_SURVEY_QUESTION() to make any updates. It's worth mentioning that I do not have enough reputation on Stack Overflow to respond directly to the previous commenter, but please note that your array is reactive. According to Vue.js documentation, modifying array items or object properties will trigger reactivity. In this case, as long as you are not adding or removing items/properties, setting an entirely new array is perfectly acceptable and will remain reactive.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through an array of latitude and longitude pairs during an AJAX request

Just starting out with PHP/AJAX and I could use some guidance. Currently, I have a leaflet map where I'm attempting to link two AJAX calls together. The initial AJAX call retrieves data based on a selected country ISO code. Subsequently, I've ut ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backen ...

Managing errors through middleware functions

Currently, I've been studying node.js on and off. I came across this question: Middleware 1: app.use(function(req, res, next) { db.load(function(err, session) { if (err) { return next(err); } ... }); }); Middleware 2: app.u ...

Utilizing SCSS to implement custom animations according to specific element IDs

How can I add different animations based on the ID of two DIVs with the same class when clicked? JSX: <div className="card"> <div id="front" className={frontClasses.join(' ')} onClick={clickedFront}> OPEN ...

Accessing a form by inputting a personal identification number

I am in the process of developing a web application form that requires users to make a payment before gaining access. After completing payment and receiving the PIN number, users must enter the number correctly to be granted access. If incorrect, access w ...

Is there a way to remove the initial number entered on a calculator's display in order to prevent the second number from being added onto the first one?

I am currently in the process of developing a calculator using HTML, CSS, and JavaScript. However, I have encountered an issue with my code. After a user inputs a number and then clicks on an operator, the operator remains highlighted until the user inputs ...

How can I combine various array values of equal length using a delimiter to create one final array?

I am trying to combine the values from 3 separate arrays, all of which have the same length. var title = ['title 1','title 2','title 3']; var description = ['description 1','description 2','descri ...

The installation of package.json is unsuccessful, as it will only proceed with an empty name and version

Having trouble installing the package.json file after updating to the latest version of Node on my Windows PC. When trying to run npm, an error was thrown. Any help would be greatly appreciated. Command Prompt C:\Users\Felix\Desktop\ ...

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...

Is it possible to input rendered HTML into a vue property?

I am currently utilizing vue-material and running into the following situation: <md-dialog-confirm :md-active="true" md-title="Make an Outbound Call" md-confirm-text="Agree" md-cancel-text="Disagree" md-content="some <p>HTML ...

What is the best way to utilize Python in order to transform a large amount of unicode into characters to create a string-like appearance?

In JavaScript, I've managed to do this: eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,99,104,101,99,107,40,41,123,13,10,09,118,97,114,32,97,32,61,32,39,100,52,103,39,59,13,10,09,105,102,40,100,111,99,117,109,101,110,116,46,103,101,116,69 ...

Maintain the button's color when clicked UNTIL it is clicked again

I am facing a challenge where I need to dynamically select multiple buttons that change color upon click. Once a button is clicked, it should change color and if clicked again, revert back to its original color. Unfortunately, I cannot rely on HTML attribu ...

Retrieve the value of the object within the mysterious index loop in JavaScript

I have retrieved search results from the data, and each time the index of my search result varies. At one point, the result may appear in the 4th index, while at another time it might be in the 100th index. How can I retrieve the rank value from within t ...

Errors are being thrown by 'npm run serve' due to the absence of FilterService

I've been working on a project using Vue.js and I keep running into an issue with npm. Every time I install it, I get errors saying that certain files are missing from the node_modules folder. When I try to run npm run serve, I encounter the followin ...

How to utilize a Jquery loop, implement a condition, and store the results in

After using dd() in PHP, the array displayed is as follows: 1 [▼0 => "1,18,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,19,20,21,22,23,24"] I need to iterate through the array and o ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

Try out the Jquery Chosen plugin, which allows you to select multiple instances of the same

I am currently using the chosen plugin to create multiple select input fields. You can view an example of this in action by following this link: By default, the plugin disables an option if it has already been selected. For instance, in the provided examp ...

Trigger an action in the clean-up function of useEffect

I am facing an issue with a form component in a Material UI <Tab /> where users can update their address information. The data is fetched from the API using redux-thunk, and the form fields are pre-filled with server data before the update occurs. h ...