Trying to assign a value to 'currentStatus' using "this" on an undefined property

In my attempt to display the state of formSubmit in vue js, I've encountered an issue. My lack of familiarity with using "this" has led to errors in the code, particularly when trying to indicate the status using "this.currentStatus".

This is the code snippet:

  const STATUS_INITIAL = 0
  const STATUS_SAVING = 1
  const STATUS_SUCCESS = 2
  const STATUS_FAILED = 3
 export default {
    name: 'Dashboard',
    data () {
      return {
        file: '',
        uploadError: null,
        currentStatus: null,
        uploadFieldName: 'photos'
      }
    },
    computed: {
      clientId () {
        return parseInt(this.$route.params.id)
      },
      isInitial () {
        return this.currentStatus === STATUS_INITIAL
      },
      isSaving () {
        return this.currentStatus === STATUS_SAVING
      },
      isSuccess () {
        return this.currentStatus === STATUS_SUCCESS
      },
      isFailed () {
        return this.currentStatus === STATUS_FAILED
      }
    },
    methods: {
      handleFileUpload () {
        this.file = this.$refs.file.files[0]
        console.log(this.file)
      },
      filesChange (fieldName, fileList) {
        // handle file changes
        const formData = new FormData()

        // append the files to FormData
        Array
          .from(Array(fileList.length).keys())
          .map(x => {
            formData.append(fieldName, fileList[x], fileList[x].name)
          })

        // save it
        this.submitFile(formData)
      },
      submitFile (formData) {
        this.currentStatus = STATUS_SAVING
        console.log(this.currentStatus)
        var clientId = this.clientId
        var reader = new FileReader()
        reader.readAsDataURL(this.file)
        reader.onload = function () {
          var asim = reader.result
          formData.append('file', this.file)
          let promises = []
          promises.push(
            performRpcWithPromise('insertContract', [
              asim, clientId
            ]).then(function (res) {
              console.log(res)
              this.currentStatus = STATUS_SUCCESS
              console.log(this.currentStatus)
            })
          )
        }
      }
    }
  }

This is how the form looks like:

<p v-if="isSuccess">
              DONE
            </p>
            {{currentStatus}}
            <form enctype="multipart/form-data" novalidate>
            <input type="file" placeholder="Velg en fil" id="file" ref="file" v-on:change="handleFileUpload()"
                   accept="application/pdf" class="input-file" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length">
              <p v-if="isSuccess">
                wow
              </p>
              <p v-if="isSaving">
              Uploading {{ fileCount }} files...
            </p>
            </form>

I followed this guide The error occurs on this line: (inside the promise)

this.currentStatus = STATUS_SUCCESS

It's perplexing to me that while

this.currentStatus = STATUS_SAVING
works and displays "1", it doesn't work inside the promise (.then).

If anyone can pinpoint why this works outside the promise but not within, I'd greatly appreciate the insight.

Answer №1

Consider using arrow function as an alternative. Here's an example:

.then(response => {
  console.log(response)
  this.currentStatus = STATUS_SUCCESS
  console.log(this.currentStatus)
})

This solution is reminiscent of this reference.

Answer №2

To achieve the desired result, you have two options: using an arrow function or a closure.

var self = this
reader.onload = function () {
  var asim = reader.result
  formData.append('file', self.file)
  let promises = []
  promises.push(
    performRpcWithPromise('insertContract', [
      asim, clientId
    ]).then(function (res) {
      console.log(res)
      self.currentStatus = STATUS_SUCCESS
      console.log(self.currentStatus)
    })
  )
}

If you prefer to use an arrow function instead, you can try the following:

reader.onload = () => {
  var asim = reader.result
  formData.append('file', this.file)
  let promises = []
  promises.push(
    performRpcWithPromise('insertContract', [
      asim, clientId
    ]).then((res) => {
      console.log(res)
      this.currentStatus = STATUS_SUCCESS
      console.log(this.currentStatus)
    })
  )
}

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

The issue of an unsuccessful Ajax call arises in a WordPress plugin when utilizing wp_remote_get

Encountering difficulties with the wp_remote_get function in my Wordpress plugin. The objective is to invoke a method within my primary public class using ajax. However, every time I attempt to make the call with the wp_remote_get function, it fails. This ...

Attempting to console.log data from within useEffect, but unfortunately no information is being logged

function FetchUserAccounts() { const [userAccounts, setUserAccounts] = useState(); useEffect(() => { async function fetchUserAccountsData() { const response = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/a ...

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

Why would one utilize window.location?.search?.split?

Could someone explain the purpose of using window.location?.search?.split('=')[1] and why the value of id is set to window.location?.search?.split('=')[1]? Code: function EndScreen() { const [score, setScore] = React.useContext(Score ...

What is the best way to keep track of the most recent 100 items?

In Angular, I want to store the last 100 items to display. Currently, I am using an array and inserting items with 'array.push'. If this method is not effective for this scenario, what alternative approach can I take? Here is a snippet of the co ...

Discover the best method for transferring MySQL data between pages

Can anyone help guide me in the right direction on how to allow a user to click a link within a PHP While Loop generated MySQL table and pass that data to another page? I've searched through similar questions but haven't found a solution that fit ...

Showing VUE Content Delivery Network

Unable to render v-for with CDN in Vue.js const Gallery = { template: '{{$t('gallery')}} <img :class="[[item.class]]" v-for="(item, index) in carousel" :src="[[item.img]]" alt="img" />' } c ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

Can you list out the directives that are responsible for generating child scopes in AngularJS?

I recently discovered that when using ng-if, it actually creates a child scope, leading to some confusion on my end. I'm curious about the reasons or benefits behind ng-if's scope creation. Can you also tell me which other built-in directives cre ...

Utilize PHP in an APP Engine Application to send an email to a Gmail address

I have a project deployed on Google App Engine where I need to send an email once a user submits the contact form. My app is successfully deployed and I have implemented an ajax request to a PHP file, but unfortunately, it's not functioning as expect ...

Serverless Functions in ZEIT Now - Customizing Routes with Parameters

I successfully implemented 4 serverless routes /api/list (GET) /api/add (POST) /api/update/:id (PUT) /api/remove/:id (DELETE) These routes were added to the api/now.json file in the following format: {"src": "/api/list", "dest": "./list.js", "methods": ...

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

Securing string parameters in Django templates for JavaScript function usage

Can anyone help me with a JavaScript function that is returning a set of objects? return Func("{{id}}", "{{name}}") I'm encountering an issue when passing strings that contain quotes, such as "Dr.Seuss' "ABC""BOOk"", which leads to invalid synt ...

Mapping three-dimensional coordinates to a two-dimensional screen location

My goal is to develop an interactive GUI for my app using threejs. I came across this informative tutorial: The tutorial provides the exact information I need, but it refers to an older release. function getCoordinates(element, camera) { var p, v, p ...

Set the android camera resolution to a lower setting automatically when a user attempts to upload a file from their browser

In my current application, I have implemented a feature that allows users to upload files. When the user clicks on the input field, they are presented with options to either select a video from their gallery or open the camera to record a new video and u ...

Merging two JSON objects in the absence of one

function fetchData(url) { return fetch(url).then(function(response) { return response.json(); }).then(function(jsonData) { return jsonData; }); } try { fetchData(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).the ...

Optimal approach for incorporating conditional tabbed routing in Vue

My current implementation involves routing with tabs that change based on the user type, which is stored in a pinia store after authentication. This is the code I have implemented: const mappingAudienceGuard = async (to: RouteLocation): Promise<true | ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

JavaScript Button with the Ability to Input Text in a TextArea?

For instance, imagine a scenario where you click on a button and it then displays various options for you to select from. Whatever option you pick will be automatically inserted into the text area. ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...