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

Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6] let array2 = [3,3,3] let result = dotProduct(array1,array2) // should return 36 Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries? ...

Tips for sending an array of inputs to the query selector in Node.js using Cloudant

Currently, I am attempting to retrieve documents from a cloudant database using node.js. While I have successfully managed to obtain results for a single input value, I am encountering difficulty when it comes to querying with an array of inputs. For a si ...

Exploring the Ins and Outs of Transition Testing in D3 v4

Previously, in older versions of D3, you were able to create unit tests that checked the state of a D3 component after all transitions had finished by flushing the timer with d3.timer.flush(). However, in D3 version 4, this has changed to d3.timerFlush(), ...

Adjust the alignment of an expansion panel header to the right using Vuetify

Incorporating the Vuetify expansion panel, I am aiming to align a specific portion of the content within the <div slote="head"></div> to the right, resulting in this desired layout: https://i.sstatic.net/tbOL8.jpg https://i.sstatic.net/22NTS. ...

Utilizing the Fetch API to retrieve a Flickr feed in JSON structure

When interacting with the flicker feed API, I have successfully received a JSON response using $.getJSON. However, when attempting to use Fetch instead, only an XML response seems to be retrieved. Example of working with $.getJSON: var flickerAPI = "http ...

Attempting to create a school project involving pizza, but encountering some technical difficulties

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>pizza ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

Is there a way to retrieve the final elements from a deeply nested array?

I've been struggling to extract the last item from a nested array of objects. I've tried using methods like flatMap, flat, filter, and splice, but so far haven't had any luck getting the desired array. const array = [ [ { total_c ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

There is an issue with the syntax in your for-loop control where a closing parenthesis is missing

When I try to navigate through the arrays from 1 to 4 in the given JSON data, Firebug shows me an error message: SyntaxError: missing ) after for-loop control [Break On This Error] for( x in LGIntake.corpCodeOptions.marketSegment.1){ StartI...aseId=0 ...

While iterating over each item in the List<string> retrieved from an AJAX GET request in JavaScript

Trying to iterate through a list of strings and display them on the page, but facing an error as described in the title... "Uncaught TypeError: response.forEach is not a function" I've looked into for loops in JavaScript, but they seem to work wit ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

Learn how to dynamically toggle the visibility of tabs in CodeMirror with a simple button click

Currently, I am developing a Python editor for a website using the Code Mirror JavaScript library. There is a button called toggle invisibles that, when clicked, displays spaces and end-of-line markers. I also wanted to show tabs, which are not supported b ...

Issue with jQuery sortable serialization when dynamically adding content is not being recognized

I've been attempting to re-order a list through ajax on sortable update. However, when I add a new item to the list via ajax after the sortable has already been initialized upon page load, it fails to recognize the new item with the "serialize" functi ...

Experiencing trouble with cross-origin resource sharing when attempting to transfer data to my server

"Access to XMLHttpRequest at 'http://localhost:3000/campgrounds/6411f03e718f68104cac045a' (redirected from 'http://localhost:5000/campgrounds') from origin 'http://localhost:3000' has been blocked by CORS policy: Response ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

Requirement: The method requires access to requestAsyncStorage, but it is currently not accessible

I encountered an issue while trying to fetch a user's data from MongoDB Atlas using Prisma client. The code I wrote for fetching the data is throwing an error. The Prisma client code is located in the prismadb file, which is imported as prisma. import ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Vue-Router: Altering the view of a parent component with a child route

In my parent view, I have a list and some metadata displayed in a right pane. I'm looking to replace the right pane component with specific item data when clicked on the list: export default { mode: 'history' base: process.env.BASE_URL, ...