Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects:

<template>
  <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
                <h2>{{joke.title}}</h2>
                <article>{{joke.body}}</article>
            <hr>
        </div>  

  </div;
</template>

<script>
import axios from 'axios';

    export default {
        name: 'showJokes',

      data () {
        return {
            jokes:[]
        }
      },

      methods: {

      },

      created() {
        axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){    
       //console.log(data); works fine
        this.jokes = data.body;
        });
    }
}
</script>

Although the result is correctly logged in the console, attempting to store it in the `jokes` array results in:

Uncaught (in promise) TypeError: Cannot set property 'jokes' of undefined

As a newcomer to Vue.js, I'm struggling with this seemingly simple error. Any assistance would be greatly appreciated.

Answer №1

You have ventured beyond this realm. It is advisable to preserve this realm within a variable.

 created() {
    let self = this
    axios.get('http://127.0.0.1:8090/api/jokes').then(function(data){    
   //console.log(data); works fine
    self.jokes = data.body;
    });
}

There exist numerous methods in How to access the correct this inside a callback? . Refer to this source for various techniques.

gratitude to Bert for the insight in comments

Answer №2

Definitely, ES6 is supported for usage.

<template>
    <div id="show-jokes-all">
        <h2>Displaying all jokes</h2>
        <div v-for="joke in jokes">
            <h2>{{joke.title}}</h2>
            <article>{{joke.body}}</article>
            <hr>
        </div>  
    </div>
</template>

<script>
import axios from 'axios';
  export default {
    name: 'showJokes',
    data () {
      return {
        jokes:[]
      }
    },
    methods: {
    },
    created() {
      axios.get('http://127.0.0.1:8090/api/jokes').then((data) => {    
      // console.log(data); // works fine
      this.jokes = data.body;
    });
  }
}
</script>

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

Execute function periodically using Vue.js

I have a requirement to update data periodically by calling a function in my Vue.js application. I am looking to call the 'listar()' method every 30 seconds and store the response in a property of vue js. If anyone can guide me on where to locat ...

Instructions for utilizing "hasPermissionTo" within a Vue template

I am struggling with my code and I am unsure how to utilize hasPermissionTo in a Vue template to verify if a role has permission to perform a certain action. <script setup> import { Link } from "@inertiajs/inertia-vue3" import { defineProps ...

Having trouble using Redirect inside a button's onClick function with React Material UI and React Router

I have been attempting to activate the Redirect React Dom using my button component within the handleMenuItemClick() function. Unfortunately, nothing seems to be happening. I've experimented with various methods, but I'm still unable to get it to ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

Challenges in Implementing Animated Counters on Mobile Platforms

My website is experiencing a strange issue with an animated counter. The counter works fine on desktop browsers, but when viewed on mobile devices in a live setting, it seems to have trouble parsing or converting numbers above 999. This results in the init ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...

Is there a way in JavaScript or jQuery to display text from an array and switch to the next piece of text in the array with the click of a button?

I currently have an array containing 13 items, all of which are text. To display the text from the array, I am using: document.write(arrayname["0"]); However, I would like to implement a functionality where users can click a button to fade out the curren ...

Javascript chart

Hello everyone, I am diving into the world of fetch API. Currently, I am faced with a challenge where I need to generate the following list items: <li>Zimmerman, Paul</li> <li>Yimmerman, Raul</li> <li>Limmerman, Caul</li> ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Instructions for altering the hue of a canvas square when the cursor hovers over it

I want to implement a feature where the color of a tile changes when the user hovers their mouse over it, giving it a whitened effect. The tileset I am using consists of 32x32 tiles. Below are the scripts for reference. MAP.JS function Map(name) { ...

Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript. Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate ...

Ensuring Element-UI table column sizes accommodate content without causing text to wrap to the next line

Is there a way to adjust the column size of an Element-UI table without causing words to break onto the next line? If you take a look at the address column in this example: https://codepen.io/rameezcubet/pen/QWLoMbr I've tried using min-width="100" ...

How can I pass a DOM element as a prop in Vue 3?

As someone who is brand new to Vue, I'm exploring the possibilities. Although it's not something I typically do, I believe achieving a similar outcome in React + JSX (untested) could look like this: render() { const el = <p>Blah <a hre ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Can you help me figure out what is causing an issue in my code? Any tips on removing a collection from MongoDB

I'm currently facing an issue with deleting a collection from MongoDB using the Postman API. The update function in my code is working perfectly fine, but for some reason, the delete function is not working as expected. It keeps displaying an internal ...