Insert the GET object into an empty object within the data and then send it back

Here is the Vue application I am working with:

new Vue({
    name: 'o365-edit-modal-wrapper',
    el: '#o365-modal-edit-wrapper',
    data: function() {
        return {
            list: {},
        }
    },
    created() {
        this.retrievePostObjects(this.list, 'applications');
    },
    methods: {
        retrievePostObjects(list, slug) {
            wp.api.loadPromise.done(function () {
                const Posts = wp.api.models.Post.extend({
                    url: wpApiSettings.root + 'fh/v1/menus/' + slug,
                });
                const allPosts = new Posts();
                allPosts.fetch().then(function(posts) {

                    console.log(posts.data);

                });
            });
        },
    },
});

console.log(posts.data) displays the following items: https://i.sstatic.net/StPRe.png

I am trying to figure out how to assign that object to my empty list: {} so I can use it in my template like this:

<button class="button" v-for="app in list.selected" :key="app.order">

Any assistance would be greatly appreciated! Whenever I try pushing the items, I end up getting an undefined result.

Answer №1

When it comes to working with JavaScript, my go-to choice is always the ES6 syntax. I find that using arrow functions within a function really helps me streamline my code and make it more efficient.

new Vue({
  name: "o365-edit-modal-wrapper",
  el: "#o365-modal-edit-wrapper",
  data() {
    return {
      list: {},
    };
  },
  created() {
    this.get_array_of_post_objects("applications");
  },
  methods: {
    get_array_of_post_objects(slug) {
      wp.api.loadPromise.done(() => {
        const Posts = wp.api.models.Post.extend({
          url: wpApiSettings.root + "fh/v1/menus/" + slug,
        });
        const all_posts = new Posts();
        all_posts.fetch().then((posts) => {
          console.log(posts.data);
          this.list = posts.data;
        });
      });
    },
  },
});

Answer №2

Chirag provided the solution earlier. However, I would suggest avoiding the use of an arrow function since it is not supported by IE. It would be better to create a separate function for handling the task, which improves code readability. You can achieve this with the following approach:

new Vue({
  name: "o365-edit-modal-wrapper",
  el: "#o365-modal-edit-wrapper",
  data() {
    return {
      list: {},
    };
  },
  created() {
    this.get_array_of_post_objects("applications");
  },
  methods: {
    get_array_of_post_objects(slug) {
      wp.api.loadPromise.done(function() {
        const Posts = wp.api.models.Post.extend({
          url: wpApiSettings.root + "fh/v1/menus/" + slug,
        });
        const all_posts = new Posts();
        all_posts.fetch().then(handlePostSuccess);
    },
    handlePostSuccess(post){
      console.log(posts.data);
      this.list = posts.data;
    }
  },
});

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

I am having trouble getting the Audio Code (a very basic code) to function properly

<audio id="myAudio" src="Avengers.mp3" type="audio/mpeg"></audio> <script> window.onload = function(){ document.getElementById('myAudio').play() } </script> Recently experimenting with some code in NotePad, a friend had ...

Using Angular to sort arrays based on the values in a separate array

I have a unique setup where there is a table containing select options in each row. The value of the select option changes based on the 'dataType' specified for that particular row. Here is an example of my Table Array: { 'name':' ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

Component library for Vue-cli 3 with built-in support for server-side rendering

I am in the process of developing a custom component library that I intend to distribute across various domains. Domains: Each domain is equipped with its own instance of Nuxt Every domain has included my-component-lib in their package.json Additional ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...

Eliminate lower values in select 1 if the value selected in select 2 is higher

I am struggling with a particular piece of code and could really use some assistance. Within my project, I have two select boxes. The first box allows users to select the "from" year, while the second box is for selecting the "to" year. What I'm tryi ...

One more time: Utilizing AJAX to save the outcome in a variable with the help of callback (undefined)

I am facing a common problem and despite my efforts, I cannot seem to resolve it. The code snippet I have provided below is causing me trouble: function get_network_from_database(callback) { $.ajax({ type: "POST", url: "load_network.ph ...

The ExpressJS app generator seems to be struggling to identify and interpret the flags

I seem to be having trouble running the express app generator with flags. For example, when I run express --version, it interprets the --version part as a target directory and creates the app there. This is happening on Windows XP SP3. Could I be doi ...

How to use the post method in Axios and Spring framework

Currently, I am a newcomer to vue.js and I am on the lookout for methods to effectively store form data using axios into a database. The technologies involved in my project are spring framework along with Thymeleaf template engine. Below is a snippet of m ...

What could be causing this excessive lag?

I've been developing a new website, but the "buttons" I'm using seem to be causing significant lag. I need help resolving this issue. You can view the website here: The problematic code snippet is shown below: <td> <a href="templi ...

How can I upload an image file using VueJS and Django Rest Framework?

Hello, I am currently in the process of editing a blog page using VueJS and Django Rest Framework. However, I am facing an issue when trying to upload a photo - I keep receiving an error message stating that "the sent data is not a file." Additionally, I a ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Instruction on inserting NativeBase footer into my React Native application?

As someone new to React Native, I am trying to include a footer bar in my app. Below is the code snippet from my dashboard.js file where I attempted to add the footer bar, but it doesn't seem to be working as expected: import React, { memo } from &ap ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Wind - Best practices for managing the status of multiple entities within a single display prior to executing the save changes function

In my system, there are three main entities: Project, Attachment, and Messages. A project can have multiple attachments and messages associated with it. The issue arises on the project detail view, where I display the project's messages and any attac ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Achieving dynamic HTML element addition through JavaScript while maintaining their record in PHP

There is an input box where the user specifies the number of new DIV elements to be added dynamically. This request is then sent to PHP via Ajax, where it prepares an HTML DIV with some inner input tags. Each DIV has a unique id attribute generated increme ...

Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin ...

What is the process for loading this image?

While browsing through this stunning website, I came across a feature that caught my eye. Can someone please explain how the designer displayed the "The magic is loading" effect: The image vanishes once the site has finished loading completely. ...