Home > Software engineering >  Cannot set properties of undefined (setting 'projects')
Cannot set properties of undefined (setting 'projects')

Time:03-24

I'm trying to push the API data to the array but I keep getting this error: "AddProject.vue Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'projects')". Any advice?

newData should be pushed to the array and from there I want to use the projects array to extract the API data.

CodePudding user response:

The error is that you are using this within a function () notation. In order to make it work as you expect, you should use an arrow function.

const test = async () => {
//...
}

CodePudding user response:

First, test() should be a method. Second, place the closing bracket in projects on the same line.

CodePudding user response:

You don't want to create a new function in methods, just add your code (but make sure mounted is async):

<script >
export default {
  data() {
    return {
      projects: [
        
      ]
    }
  },
  async mounted() {
    const data = await fetch("https://jsonplaceholder.typicode.com/posts");
    const newData = await data.json();
    console.log(newData)
    this.projects = newData;
  }
}
</script>

You could do this:

  async mounted() {
    this.projects = await fetch("https://jsonplaceholder.typicode.com/posts").then(raw => raw.json());
  }

Example

  • Related