Error: When trying to set a property on an undefined object in vue.js, a TypeError is thrown because the object is not defined

I'm encountering an issue while attempting to populate my empty object with data received from a JSON server API. The problem persists on the same line repeatedly:

Uncaught (in promise) TypeError: Cannot set property 'itemListModel' of undefined at eval

Here is my code snippet:

data: function() {
return {
itemListModel: {}
}
}

methods: {
   getAllItemsFromDb: async () => {
    const url = 'https://localhost:44339/ListAll';
      await axios.get(url, {
    headers: {
        'Content-Type': 'application/json'
    }}).then((response) => {
         this.itemListModel = response.data
    })
    }
}

computed : {
   itemResultsFromDB: function(){

      return this.itemListModel
    }
}

I've also referred to a similar question here: Uncaught (in promise) TypeError: Cannot set property of undefined with Axios

Despite that, I can't seem to identify what's causing the discrepancy in my implementation?

Answer №1

The culprit in this situation appears to be the arrow function. I suggest converting getAllItemsFromDb into a traditional function:

methods: {
   function getAllItemsFromDb() {
      const url = 'https://localhost:44339/ListAll';

      axios.get(url, {
         headers: {
            'Content-Type': 'application/json'
         }
      }).then(function(response) {
         this.itemListModel = response.data
      })
   }
}

Answer №2

When calling the getAllItemsFromDb function, make sure to utilize async/await for axios.get() instead of using a .then() block. Here's how you can achieve this:

getAllItemsFromDb: async () => {
  const apiUrl = 'https://localhost:44339/ListAll';
  const response = await axios.get(apiUrl, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

  this.itemListModel = response.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

Keep only the selected properties in the object and eliminate all others

I am faced with a challenge where I need to eliminate array members that do not have a certain property. Take for example this scenario: const idToKeep = 1; const objList = [{ id: 1, name: 'aaa', }, { ...

Following a successful login, the User ID fails to store in the session

I am a beginner in the world of coding and I am currently working on one of my first apps. I have encountered an issue with my log in function. After user registration, the user id is successfully saved in the session object. However, it does not save into ...

Resolving AngularJS routes while invoking a controller with ng-include

Feel free to check out my Plunkr demonstration by clicking here. In my application's app.js file, I've defined two controllers along with a route provider that includes a resolve function for the TestController. var app = angular.module(' ...

Creating a unique Vue.js component with an HTML <select> element and v-model that adheres to W3C standards

I recently started using Vue.js with Nuxt.js and I am working on creating a reusable Select component that follows W3C compliance guidelines. Thanks to the help of @Jasmonate's answers, I successfully created this component. However, I noticed that t ...

Attempting to fetch a .ico file from the server side (Node ExpressJs) to the client side (ReactJS) triggers a 'TypeError: res.blob is not a function' error

My web application utilizes ReactJs on the front-end and NodeJs express on the back-end. I encountered an issue while attempting to retrieve and display a .ico file on the client-side using this code: Client side: async function getIcon() { try { ...

A guide to delivering static images using NestJS

I recently started learning the MEAN stack and while exploring Express, I came across an additional layer in the framework called NestJS. It had everything I needed and the Angular-like syntax was perfect for me. However, each new step has been a nightmar ...

Unexpected identifier error encountered in iPhone IOS 10 Safari while attempting to parse JSON with the presence of the keyword "function

Currently, I am facing an issue while troubleshooting an error on a client's website that only seems to occur on iOS 10 devices. The clients have mentioned that it was working fine prior to upgrading their devices to iOS 10 and reverting back to iOS 9 ...

Avoiding the loading of textures on the obj model in three.js is essential

Can anyone assist with why the texture is not loading? I attempted to load the texture onto a separate mesh in obj file but it's not working, giving an error. Can someone explain why the material is applied but the texture is not loading? var manage ...

React Router v6 is throwing an error stating that within the <Routes> component, all children must be either a <Route> or <React.Fragment>

While the code snippet below may have worked perfectly fine in React Router v5, it's causing an error in React Router v6. Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React ...

Encountering an issue: Unhandled error - Unable to access property 'parentNode' of a null value

I'm attempting to add a new div next to another div using the ComponentID of the first div as a reference. I want to place the second div parallel to the first one, like this: <div> <div id="userActivityStatusMenu-1110">Neighbor 1< ...

Unraveling Complex JSON Structures in React

Having trouble reading nested JSON data from a places API URL call? Look no further! I've encountered issues trying to access all the information and nothing seems to be coming through in the console. While unnested JSON is not an issue, nested JSON p ...

Utilizing the 'Day' Function in Visual Basic to alter the date and submit a form according to the day of the week

I have been developing a Windows application that utilizes the WebBrowser control to automate form filling based on specific criteria. One challenge I encountered is with dates on certain forms, where different rules apply depending on the day of the week. ...

The functionality of the Binding class appears to be malfunctioning in relation to the value of the attached variable

One interesting aspect of my code is how the presence of the banner-visible binding class is determined by the value of my showMainBanner computed property: <div :class="['view view-index', { 'banner-visible' : showMainBanner }]"> ...

Javascript enables the magnetization of cursor movements

Can a web page be designed so that when users open it and hover their mouse over a specific area outside of an image, the mouse is attracted to the image as if by a magnet? Is this idea feasible? Any suggestions would be appreciated. ...

The dynamic pages specified by the graphql query in the gatsby-node.js file are not being generated by Gatsby.js as expected

Even after running gatsby clean followed by npm run develop, the issue persists... Several individuals familiar with the Gatsby framework have reviewed my gatsby-node.js file, but the problem remains puzzling... Below is a snippet of my gatsby-node.js fi ...

How can data be shared across different JavaScript functions?

I have two dropdown lists where I'm trying to pass the selected values for both to another function. I know that the way I am currently doing it is not correct, but I have been staring at this code for so long that I can't seem to find the probab ...

The Axios pre-flight request is receiving the Access-Control-Allow-Origin response, but it's indicating an error because the header is missing

Here are the headers received after making a preflight options call: Access-Control-Allow-Headers: * Access-Control-Allow-Methods: POST Access-Control-Allow-Origin: * Allow: POST,OPTIONS However, we are still encountering an error: The C ...

Here's a unique way to describe the issue: "Exploring the process of

Scenario: During my testing, I encountered an issue with mocking two calls to external APIs. Despite using the 'axios-mock-adapter' library and ava framework, I was only able to successfully mock the first call while the second one remained unmo ...

What is the best way to import a JSON file in VueJs without the need for compilation?

I am facing an issue while developing a VueJs application. I have a JSON file containing an array of objects, and when displaying based on search criteria, it results in generating a very large app.js file, causing the application to boot slowly. Currentl ...

Achieve Seamless Scrolling Without Using JavaScript - It Only Takes a Single Line of CSS!

Could anyone advise on how to achieve smooth scrolling without using JavaScript, with just a single line of CSS? I am working on creating a website where I want to implement smooth scrolling. I am currently working on a website project and would like to ...