Vue.js application fails to retrieve data with undefined method

I have a query that I need some assistance with. I am trying to retrieve data but seem to be facing difficulties in passing the data to my method.


The code snippet below shows the component and vue.js app I am working with:

Vue.component('favorites-edit-component', {
   template: `
   <div class="column is-half">
      <button class="button is-fullwidth is-danger is-outlined mb-0">
        <span>{{ name }}</span>
        <span class="icon is-small favorite-delete" v-on:click="$emit('remove')">
          <i class="fas fa-times"></i>
        </span>
      </button>
    </div>
   `,
    props: ['name'],
});

new Vue({
    el: '#favorites-modal-edit',
    data: {
        new_favorite_input: '',
        favorites: [],
        next_favorite_id: 6,
    },
    methods: {
        add_new_favorite: function() {
            this.favorites.push({
                id: this.next_favorite_id++,
                name: this.new_favorite_input
            })
            this.new_favorite_input = ''
        },
        get_favorite_menu_items: function() {
            wp.api.loadPromise.done(function () {
                const menus = wp.api.collections.Posts.extend({
                    url: wpApiSettings.root + 'menus/v1/locations/favorites_launcher',
                })
                const Menus = new menus();
                Menus.fetch().then(posts => {
                    const test = posts.items.map(item => {
                        const items = {};
                        items['id'] = item.ID;
                        items['name'] = item.post_title;

                        console.log(items);
                    });
                });
            })
        }
    },
    created () {
        // fetch the data when the view is created
        console.log(this.get_favorite_menu_items());
        this.get_favorite_menu_items();
    },
});

I aim to extract the data from the method get_favorite_menu_items and pass it to favorites: [].

Currently, within the created () call, I am receiving an undefined result for this.get_favorite_menu_items();.


Upon logging items inside my method, I notice that the objects are duplicated, which is not desired. To resolve this, I want to achieve the following:

  1. Retrieve two objects from the method only.
  2. Create an array of these objects and then assign the array to favorites: [].

When I log test, I see the return as:

[undefined, undefined], [undefined, undefined]
.

Menus.fetch().then(posts => {
    // this.favorites = posts.items;
    const test = posts.items.map(item => {
        const items = {};
        items['id'] = item.ID;
        items['name'] = item.post_title;
    });
    console.log(test);
});

Your help on this matter would be greatly appreciated!

Answer №1

Make sure to include a return value within your map function for it to work correctly. Here's an updated version:

this.selection = posts.items.map(post => {
  const postInfo = {};
  postInfo['id'] = post.ID;
  postInfo['title'] = post.post_title;
  return postInfo;
});

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

AngularJs: Tips for running functions synchronously

Is there a way to ensure that three services are executed synchronously in AngularJS? I'm facing an issue where my logic fails because the $http.get() services are running asynchronously. The goal is to read JSON fields from each service response, set ...

Having trouble with your Ajax call to an express route?

Trying to initiate an ajax call from a JavaScript file to an express route within a Node.js application, while keeping in mind that the JavaScript file is also part of the same Node.js application. Encountering an issue where the data passed to the route ...

Combine the elements of an array to form a cohesive string

As a newcomer to Javascript, I am feeling a bit puzzled about this conversion. var string = ['a','b','c']; into 'a','b','c' ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...

Implementing a click function that toggles between adding and removing a class, keeping track of the number of clicks, and utilizing localStorage to prevent repeated clicking in the

Hi there! I'm currently working on a simple widget that features a clickable icon and a counter next to it. When the icon is clicked, it should toggle between an empty heart and a filled heart using addClass/removeClass. Additionally, each click incr ...

Encountering a syntax error while utilizing jQuery AJAX

Recently, I've started learning jQuery and came across an AJAX example that intrigued me. The task at hand is to pass a PHP variable to another PHP page without refreshing the entire webpage. After some tinkering, I managed to come up with the code sn ...

The react-datepicker component is unable to set the state to the format dd/MM/yy

The date is currently shown in the correct format (31/08/21), but when onChange gets triggered, startDate changes to something like this: Tue Aug 31 2021 21:29:17 GMT+0200 (Central European Summer Time) Is there a way to maintain the display format I wa ...

Tips for declaring the OpenLayers map object globally

I have successfully created a map with ol 6 and added an OSM layer. Now I am trying to incorporate a vector layer that is coded in another JavaScript file, using the same 'map' object. Despite my efforts to declare it globally, it doesn't se ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...

An error occurred while trying to access properties of null during a promise, specifically when trying to read the 'parentNode' property - triggered by calling router.push({})

After updating my dependencies, I encountered an issue every time I clicked on a button to navigate to the next page. The error message Uncaught (in promise) TypeError: Cannot read properties of null (reading 'parentNode') would appear, even thou ...

Select dropdown options in Material UI are overlapping

Exploring React for the first time and utilizing material-ui's select button feature. It displays highlighted text based on user input, but ideally this highlight should disappear upon selection of an element. https://i.stack.imgur.com/2ccaS.png How ...

Implementing an infinite scrolling feature using Javascript within a specified div element

I'm currently working on implementing an infinite loading feature using JavaScript. I came across this helpful resource that explains how to achieve infinite scrolling without jQuery: How to do infinite scrolling with javascript only without jquery A ...

Following the path of JavaScript function calls

As I explore my Chrome console, I find myself puzzled by the mystery of the JavaScript file that gets called when I import a file from my computer after clicking on an input file tag. It seems to happen without any clear indication of which method triggere ...

Reset and recreate a bootstrap-slider

I have implemented the Bootstrap-slider plugin from https://github.com/seiyria/bootstrap-slider using version 10 (also tested with v11) in my code: /* Enhancing style - Bootstrap slider used */ $('.bs_sliders').each(function () { var id = &ap ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Setting a flag in jQuery to halt the submission loop

Hey there, I'm grappling with a little logic issue and could use some guidance. The code I have seems to be functioning well, but I'm stuck on how to implement a flag to prevent an endless loop. So, here's the scoop: I have a login page whe ...

Steps to configure useState to manage data within an object

Having trouble setting an object with useState in my code. Despite my effort, I am only getting the initial value for the object named setWishlist. Can someone spot what mistake I am making? const CenterModal = props => { const [modalData, setModalDa ...

The Mongoose connection status is consistently showing as 0

Utilizing nodejs and mongoose to establish a connection with my MongoDB Database. I am attempting to check the connection state, specifically if it is connected or not. I am using mongoose.connection.readyState to achieve this. The connection seems to be ...

Matching the scope property in AngularJS directives

I am currently working on creating a custom directive that will perform regex validation on specific input fields. The goal is for the directive to determine which regex pattern to use based on an attribute provided in the input element. Here is an exampl ...