Focus automatically on an input component when the value in the Vuex store is updated in Vue

Here's the code snippet from my component:

//template
<v-select ref='ItemSearchSelect' :options="options"></v-select>
...
//script
created: function () {            
         this.$store.subscribe((setFocusSearch, state) => {
                if (setFocusSearch.type == 'setFocusSearch' && setFocusSearch.payload == true){
                    this.$refs.ItemSearchSelect.$refs.search.focus()
                    this.$store.commit('setFocusSearch',false)                    
                }
        })
    }, 

This is the mutation function in my store that can be accessed from any other component:

setFocusSearch(state,val){
      state.focussearch = val;
    },

Sometimes it's working perfectly, but at times I encounter an error in the console and the focus feature fails to work:

Uncaught TypeError: Cannot read property '$refs' of undefined
    at eval (ItemSearch.vue?d78c:38)
    at eval (vuex.esm.js?2f62:392)
    at Array.forEach (<anonymous>)
    at Store.commit (vuex.esm.js?2f62:392)
    at Store.boundCommit [as commit] (vuex.esm.js?2f62:335)
    at VueComponent.focusSearch (ShoppingCart.vue?0f5b:96)
    at keydown (eval at ./node_modules/cache-loader/dist/cjs.js?
    ...

This issue consistently arises under a specific scenario:

I navigate to a view with my ItemSearch component and another component that triggers the store mutation. Everything works fine at this point. Then, I switch to a different view unrelated to the components and return to the original view using router push. The error occurs when the mutation is triggered again.

Any insights on what might be causing this?

Answer №1

Once your component is no longer in use or destroyed, the mutation subscription remains active within the store. As a result, the reference to 'this' in your subscriber function becomes null or undefined.

In order to address this issue, it is crucial to unsubscribe from the mutation when your component is being destroyed. Refer to https://vuex.vuejs.org/api/#subscribe...

To stop receiving updates, simply call the provided unsubscribe function.

Here's an example implementation:

mounted () {
  this.unsubscribeMutation = this.$store.subscribe(...)
},
beforeDestroy () {
  this.unsubscribeMutation() // invoke the unsubscribe function
}

I made sure to use the mounted lifecycle hook rather than created. This decision ensures that your $refs are fully populated before any operations are carried out, adding an extra layer of security.

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

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

How can I design a form that resembles the sign-in form used by Google?

Currently, I am in the process of creating a contact form for a website that is inspired by the design of Google's material sign-in form. I have successfully implemented an effect where clicking on the input field causes the label to change its posit ...

Generate checkboxes by utilizing the JSON data

Here is a snippet of my JSON data: [ { "type": "quant", "name": "horizontalError", "prop": [ 0.12, 12.9 ] }, { "type": "categor", "name": "magType", "prop": [ ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Having trouble loading a JSON file in three.js?

I have been trying to load a JSON image in Three.js by following a tutorial video. However, despite copying the code exactly as shown in the video, I am not able to see anything in the browser when using my own images. The JSON file is downloaded from clar ...

The express-unless plugin in Node.js allows you to exclude specific paths from the middleware.auth

I need help implementing express-unless to exclude a /health path from using middleware.auth. Unfortunately, I am facing syntax issues and unable to test this locally. Using localSite == true is not compatible with my environment. The error logs are shown ...

Issues arise when using Jquery events in conjunction with AngularJS causing them to function

I have encountered an issue with my AngularJS menu code. I am sending an array to prepare the menu when the document loads. In this sequence, I have also added a click event to the generated menu. However, the click event does not fire if it is placed befo ...

Is it possible to use JavaScript to load, edit, and store text files?

Hey there, I have a text file that needs some find and replace operations done on it within the browser. My coding skills are still in the beginner stage, so creating web apps from scratch feels overwhelming right now. All I want to do is upload the file, ...

Automatically unset session variable 'unsetted' using a simple line of code

Why does the session information not get saved? When I reload the page, the session variable 'mucciusersess' disappears. What could be causing this issue? Thanks... I have a cookie on the client-side with a value like 'mucciuserid' se ...

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

What is the best way to connect a Jquery plugin to a table within a partial view following an ajax request?

I have a main view that utilizes a partial view to display items in a table format. Main View (Enclosed within a div, it references the Partial View) <div id="divList"> @Html.Action("_list") </div> Partial View (Displaying a list of it ...

Adjust the database table when a session expires in PHP

Within my PHP code, there is a session timeout feature that triggers after 60 minutes of inactivity. This code snippet resides in the file /mno.php, where both the login and logout functionalities are also implemented. /mno.php if (isset($_SESSION[' ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

I intend to use the v-for directive in Vue to create a table

Below is an example of a JavaScript array. mydata:[1,2,3,4,5,6,7,8,9] This is the desired result in table format: 1 2 3 4 5 6 7 8 9 Using vanilla HTML, you can achieve this with a table: <table> <tr> <td>1</td><td>2& ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

JavaScript News Scroller for Horizontal Display

After searching through numerous websites, I have yet to find the ideal horizontal news scroller for my website. My specific requirements include: Must provide a smooth scrolling experience Scroll from right to left covering 100% width of the browser ...

Using Jquery to add new HTML content and assign an ID to a variable

Here is some javascript code that I am having trouble with: var newAmount = parseInt(amount) var price = data[0]['Product']['pris']; var id = data[0]['Product']['id']; var dat ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

Featuring data utilizing Ajax JSON in CodeIgniter

How can I display the data using AJAX? After making the data call to the controller, the JSON data is available but the data for "name", "address", and "telp" based on the "id_data" is not showing up. How can I display this data? Views <input id="id_d ...