VueX Error: The store property is undefined and cannot be read

In my vue.js store, I am able to access the state parameters within the computed section of a component:

computed: {
    BASE_URL () {
    return this.$store.state.BASE_URL;  
  }

However, when attempting to access the store in the methods of the same component:

  methods: {

    register: function () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then(function(data){
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  
 },

An error is triggered in the console:

Uncaught (in promise) TypeError: Cannot read property '$store' of undefined

I have also tried $store without including this, yet encountered the same issue.

What could be causing this problem? How can it be resolved?

Answer №1

Instead of using a JavaScript function, consider switching to an arrow function for better functionality. Give this method a try and see if it resolves your issue.

 methods: {
    register () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then( (data) => {
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  

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

Exploring the Node.js view object within a function and delving into the reasons why a property of

As a beginner in programming, I am seeking tips on how to effectively learn node.js. Currently, I am utilizing the "Learning Behavior Driven Development with JavaScript" book for my learning journey. I would greatly appreciate any advice on how to view ob ...

I am looking to implement a Laravel broadcast feature to dynamically update an HTML attribute in real time

CODE SNIPPET FOR PROGRESS BAR <div class="ui fluid inverted segment" id="app"> <div class="ui small header">ONGOING TASK ANALYSIS </div> <div class="ui indicating big progress" id="taskprogress" :data-total="total" :data-value ...

Master the art of handling JSON data within an Angular controller

I've been spending a day attempting to manipulate a JSON in order to display a table, but I can't seem to achieve the desired outcome. My goal is to showcase statistics in a table for each town. If a town has multiple lines, I want to display a ...

Nuxt.js Button Dropdown Widget

Currently, I am in the process of creating a button similar to a dropdown. This particular button is meant for printing and downloading documents. Here is the code I have implemented: <template> <v-menu transition="s ...

Display a 404 page on Vue router when the ID does not match

When it comes to displaying a 404 page if a parameter doesn't match, I'm a bit puzzled. For instance, if the user name is “joe” and someone tries to access “/joe/categories”, then the categories component should be displayed. Now, I want ...

Differences between Jquery's Find Method and ID Attribute

In my search for efficiency, I am currently exploring ways to quickly access an element. Which method is faster: $('body').find('#elemID'); vs. var id = $('#elemID'); ...

Issue with MUI toggle switch not updating display and value upon clicking once

I'm currently experiencing issues with a Material UI toggle switch in my project. Initially, when the component loads, the console log displays the correct value. However, when I toggle the switch from 'yes' to 'no', the visual cha ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...

Discrepancy between Laravel Vue: console logging Axios POST response and network response apparent

https://i.stack.imgur.com/vO05x.png Within my Laravel vue app's backend, I am noticing an inconsistency in the data being sent and received. Even though the data is supposed to be the same, the two console logs are showing slight differences. DATA ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

localization within vue component

if (self.form.pickupTime == '') { self.formError.pickupTime = 'Please enter a pickup time that is ready for collection.'; status = false; return status; } else { self.formError.pickupTime = ''; } I am struggling ...

No data found on Angular TypeScript page with an empty array

Incorporated a function called 'getQuestionsWithInterviewId' to populate my 'Questions' string, but it appears empty when I attempt to call it within the ngOnInit and ngAfterContentInit methods and log the result in the console. import ...

What is the best way to distinguish a particular item in a <select> element and include a delete button for each row using jQuery?

1.) I've set up a nested table and now I want to ensure that when the 'Delete' button within the child table is clicked, its corresponding row gets deleted. 2.) I have a <select> tag. The issue is how can I implement validation to che ...

What is the process to enable a tab in AngularJS using Foundation's tab feature?

Currently, I am utilizing AngularJS in conjunction with Foundations. Visit the official website for more information Within my page, there are two tabs that are functioning correctly as shown below: <tabset> <tab heading="tab1"> </tab ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

The posenet TensorFlow model results in Node.js do not contain any position detail for coordinates "x" and "y"

I executed the posenet model on node v8.11.0. Below is the code snippet that I utilized. Unfortunately, the output results are not displaying the position of each pose; instead, it simply shows [Object]. It seems like there might be a canvas-related issue. ...

The process of dynamically loading and changing Vuetify Tabs is a dynamic and versatile feature

I'm currently implementing Vuetify Tabs to showcase my items. The Tabs are being utilized to exhibit a swipeable list of items that can be approved or disapproved by the user. Once an item is approved, it should be removed from the list. However, I&a ...

Experiencing difficulty importing .pem files into Express

Referred to by this previous inquiry which went unanswered: I've stumbled upon something peculiar. Despite my efforts, I am still unable to import my certificate. Every time I attempt to run my Node/express application, it crashes with the same error ...

Arrange JSON data in ascending order based on the dates, starting with the most recent date, by utilizing jquery

I'm in need of assistance on sorting a list of articles from an external json file based on their creation date. Can anyone provide guidance? Currently, I am fetching the data using AJAX and displaying only 6 results, but I'm facing difficulties ...