Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message

TypeError: Cannot set property 'randomWord' of undefined
specifically at the line:
this.randomWord = response.data.word;

Confirming that console.log(response.data.word) does display a string.

Vue Component Structure:

<template>
  <div>
    <h2>Wordnik Random Word</h2>
    <button class="button" @click="getWord">Random Word</button>
    <p>The randomly generated word is: {{ randomWord }}</p>
  </div>
</template>

<script>
const axios = require('axios')

export default {
  name: 'RandomWord',
  data() {
    return {
      randomWord: '',
    }
  },
  methods: {
    getWord() {
      axios.get('https://api.wordnik.com/v4/words.json/randomWord', {
          params: {
            api_key: 'XXXXXXXXXX',
            hasDictionaryDef: true,
            minCorpusCount: 4
          }
        })
        .then(function (response) {
          console.log(response.data.word);
          this.randomWord = response.data.word;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
  },
}
</script>

Answer №1

Here's a quick solution: Using an arrow function in the initial promise would have been more effective.

Revised code snippet:

.then(function (response) {
          console.log(response.data.word);
          this.randomWord = response.data.word;
        })

Refined version with arrow function:

.then((response) => {
          this.randomWord = response.data.word;
        })

For further clarification, check out this resource: Title of Resource Here

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

Is there a way to break this down so that I can obtain an array containing the data for each month?

My JSON structure is as follows: "meterConsumption": [ { "month": 1, "details": [ { "timestamp": "2020-01-01", ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

JavaScript JQuery alert popup fails to display

I have been attempting to create an alert pop-up using JQuery that will display when a user clicks on submit without filling out the form. However, when I test my code by leaving the form empty and clicking 'submit', the page just refreshes with ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Guide to utilizing the THREE.OBJExporter

I've come across this post, however, when I am utilizing var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); var mesh = new THREE.Mesh( totalGeom, material ); THREE.OBJExporter.parse( mesh ); Error message shown is: Uncaught Typ ...

The function of slidetoggle is malfunctioning when clicked

I currently have two dynamic containers with one displaying grouped boxes, quantities, and totals, while the other shows detailed information. Both container values are added dynamically at runtime. By default, the grouping container is displayed on the p ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

tsconfig.json: No input files were detected in the configuration file

I am encountering an issue with my tsconfig.ts file where it says "No inputs were found in config file 'd:/self-study/Web/Learning/Express/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude&a ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

Solution: The issue where the children's onChange event was not updating the parent in Ant Design was discovered to be due to the Select and Table components nested inside a Tab not changing according to the pageSize

I'm facing an issue with updating a parent element when the children's onChange event is triggered. Specifically, I have an Ant Design Select and Table inside a Tab that are not reflecting changes in the pageSize value. Although setPageSize func ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

An error has occurred in React with a nested JSON object, suggesting that it may actually

I encountered an interesting error with my React file using Axios. While the data retrieval from my post works fine, I am facing a problem when trying to display all posts on one page. Despite my efforts to find a solution, I have not been successful. Bel ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

Tips on retrieving the API response using AJAX

Currently, I am attempting to retrieve the API response from Flickr using Ajax in my application built with Laravel. To accomplish this, I have established a specific Route and function dedicated to handling API calls. //Route.php Route::post('/getlo ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

I am looking for a VueJS component that replicates the functionality of http://jsfiddle.net/NuWna/2/

I am in search of a VueJS Card Component that resembles this particular example: http://jsfiddle.net/NuWna/2/ Struggling to convert the jQuery code into VueJS syntax $(document).ready(function(){ $(".slide").hover(function(){ $(this).find(" ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Error: The function imgPreload cannot be executed because $ is not recognized as a function

I'm encountering an issue with calling a JavaScript function. Here's the code snippet I'm using: <script type="text/javascript" src="<?php echo base_url().'assets/'?>js/jquery-1.9.0.min.js"></script> <script t ...