Error: Cannot set value on a property that is designated as a getter-only in Vue.js using

My current task involves taking an image as input, converting it into a base64 string, preparing a payload containing the base64 string, and sending a post request to the backend. I then need to retrieve the response data and preview the base64 image from the response object.

However, when I run the code, I encounter the following error inside the axios request:

Error: "setting getter-only property "result""

It's worth noting that console.log(response) successfully prints the response data. But unfortunately, console.log('SUCCESSFUL') does not print due to the error.

<template>
  <div id="Uploader">
    <input type="file" id="file" ref="file" v-on:change="handleFileChanges" multiple/>
    <button v-on:click="upload_picture">Submit</button>
    <div> Hello {{result}}</div>
  </div>
</template>

<script>

import axios from 'axios';


export default {
  name: 'Uploader',

  data() {
    return {
      file: '',
      values: '',
      result: [],
    };
  },

  methods: {
    handleFileUpload() {
      [this.file] = this.$refs.file.files;
    },
    handleFileChanges(e) {
      const reader = new window.FileReader(); // if window i
      // s not used it says File READER is not defined
      reader.onload = function oldyfunt(event) {
        // dispatch fileAttached to state UI postEditor with event.target.result as read dataURL
        this.values = event.target.result;
        console.log('VALUES');
        console.log(this.values);
        const data = {
          images: {
            image1: this.values.split(',')[1],
          },
        };
        axios.post('http://0.0.0.0:9094/analyze',
          data,
          {
            headers: {
              'Content-Type': 'application/json',
            },
          }).then((response) => {
          console.log(response);
          this.result = response.data;
          console.log('SUCCESS!!');
        }).catch((error) => {
          console.log(error);
          console.log('FAILURE!!');
        });
      };
      reader.readAsDataURL(e.target.files[0]);
    },
    upload_picture() {
      console.log(this.values);
    },
  },
};
</script>

Answer №1

Make a simple adjustment

reader.onload = function updateFunction(event) {

with

reader.onload = (event) => {

This tweak should resolve your issue

this refers to the current scope, where in this case it points to the updateFunction instead of the Vue instance

You can delve further into arrow functions here

Answer №2

When working with axios callback functions, it's important to note that you cannot use the this reference directly inside them. Instead, define the function outside and pass it as a parameter:

methods: {
  ...
  handleResponse(response) {
    console.log(response);
    this.result = response.data;
    console.log('SUCCESS!!');
  },
  handleFileChanges(e) {
    ...
    const afterPostRequest = this.handleResponse;
    reader.onload = function(event) {
      ...
      axios.post('http://0.0.0.0:9094/analyze',
        ...
      ).then(afterPostRequest).catch((error) => {
        console.log(error);
        console.log('FAILURE!!');
      });
    };
    ...
  },
  ...
},

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

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

Sending a message in the DELETE route using express.js

I'm having trouble displaying a message after deleting a user. I attempted to use req.session properties and then retrieve them in the GET route, but they seem to not be available. Can anyone suggest a solution for fixing this code? router.get("/", ...

"Dynamic Addition of Textboxes to Webpages with the Help of jQuery

Currently, I am facing a challenge in adding a textbox to a webpage in ASP.NET MVC using jQuery. My goal is to have a button that, when clicked, appends a text box to the existing collection of Textboxes with a specified class. Below is the jQuery code sni ...

Modify a JavaScript object in JSON format using another object as reference

Consider two JSON formatted JavaScript objects: obj1 = { prop1: 1, prop2: 2, prop3: 3 } obj2 = { prop1: 1, prop2: 3 } In the context of jQuery or Angular, what is the recommended practice to update obj2 into obj1 while also re ...

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...

What steps are needed to access the Root in the setup function of a Vue 3 component?

I recently built a Vue App and incorporated Vuex for state management. Here is how I set up my app initially: import { createApp } from "vue"; import axios from "axios"; import App from "./App.vue"; import router from "./ ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

Optimal method for presenting informative content at the top of a webpage: Harnessing the power of JavaScript

Could you check out the image linked above? There appears to be a css animation on the bright yellow arrow. Issue: I am working on a page where I need to guide users' attention (possibly with a yellow arrow) and have it disappear automatically ...

The Vue.js application which utilizes Vue I18n encountered the error message: "Unable to define i18n due to TypeError"

I am currently working on implementing internationalization in my Vue.js project using Vue I18n. Although I've been following the documentation found at , I encountered the following error message: [Vue warn]: Error in render: "TypeError: i18n is un ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

What is the best way to import a Vue.js component using the @/xxxx/component.vue file path?

I am attempting to implement a Vue.js template called Core-UI with Laravel, but I am encountering an issue with this file. When I compile it, I receive the following error: These dependencies were not found: * @/containers/DefaultContainer in ./resources ...

An uncaught error occurred in ReactJs while trying to read the property 'map' of an undefined variable within the {Component} component

As I pass my array to the props of the sidebar component and try to access it in my child component... After saving the code and checking the browser, an error message pops up: https://i.stack.imgur.com/6cPY8.png import React, { Component } from 're ...

What is the best way to incorporate objHoles into every individual object?

I need to assign specific attributes to each player in a game. Each player should have different sets of holes, with each hole having its own win, lose, push, and points values ranging from 0-20. Is there a simple way to accomplish this task? As a beginn ...

What is the mechanism behind the functioning of StackOverflow's notification system?

Could you explain the technique that is utilized to transmit and receive data from the client to the server? How does it manage to provide almost real-time results when new changes take place? Can anyone demonstrate the code being used for this process? ...

Incorporate a Flask variable into a webpage seamlessly without refreshing the page

I am facing a challenge in importing the variable test_data from Flask to my webpage without having to reload it. I have tried clicking a button, but haven't been successful so far. Any suggestions? Flask: @blueprint.route('/data_analysis' ...

Jade iterates over each object element, assigning its children to their respective parent elements

I have a JavaScript Object named "boards". [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"}, {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}, {"id":3,"parent_board":1,"title":"Lorem 1-1"," ...

Data merging in Firebase 9 and Vue 3 is not functioning properly

I am facing an issue with merging data in my firebase database. I consulted the documentation at https://firebase.google.com/docs/firestore/manage-data/add-data for guidance. After attempting to merge data using setDoc, I encountered an error (Uncaught Ty ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...