Why doesn't vuex4.0 function properly as hooks when used within a Vue3 onMounted async function?

When foo() is completed, I need to choose one of bar1(), bar2(), or bar3() as the actual function to be sent to the web socket and store the callback value in vuex.

1. bar1(): If I include bar1() in the onMounted scope, it does not work and the store becomes undefined.

2. bar2(): Passing the argument "store" into bar2() in XXX.vue makes it work successfully.

3. bar3(): Surprisingly, even if bar3() is not in the onMounted scope, it still works without waiting for foo() to complete, which is not the expected behavior.

The msg_state stores something in store.state and I want to commit it to update its value.

Questions:

  1. What sets bar1(), bar2(), and bar3() apart from each other?
  2. Why does bar2() work as bar() while bar1() does not?
  3. Is the success of bar3() due to it being inside the setup() scope rather than the onMounted() scope?
// In socket.js
// Does not work
import { useStore } from 'vuex'
export const bar1 = async(input) =>  {
// store is undefined
const store = useStore()
socket = io(url)
    socket.on('message', (msg)  = {
        // commit is not defined
        store.commit("msg_state", msg) 
    })
}

// Works
export const bar2 = async(input, store) =>  {
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

// Works but not asynchronous
import { useStore } from 'vuex'
export const bar3 = (input) =>  {
const store = useStore()
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

//In XXX.vue
import bar from '@/util/socket.js'
...
export default {
    setup() {
        const xxx = reactive({input: oldVal})
        const store = useStore()
        onMounted(async () => {
        //{input: oldVal}
        await foo()
        //{input: newVal}

        // option1: bar1 as bar
        await bar1(xxx.input) // counldn't work

        // option2: bar2 as bar
        await bar2(xxx.input, store) // this could work

        })
        // option3: bar3 as bar
        bar3(xxx.input) // this could work but not async
    }
}

Answer №1

bar1 and bar3 are both incorrect because hooks should generally be called within the `setup` function. Additionally, `bar2` does not require access to the entire store.

Converting functions to `async` could lead to a semantic error as they are asynchronous but do not involve promises. Furthermore, if there is a subscription to `message`, it cannot easily be translated into promises unless it's a one-time occurrence.

If `commit` is being used outside of an action for a one-time event, it means that store-specific logic is spread throughout the application. It would be more efficient to include the entire `bar` function in a Vuex action:

const bar = async ({ commit, state }, input ) =>  {
  // assuming socket is part of the state
  await new Promise(resolve => {
    socket.once('message', (msg) => {
      commit("msg_state", msg) 
      resolve(msg);
    });
  })
}

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

How can I retrieve XML information from a webpage?

I've been trying to incorporate some basic JSON data into my website, but despite experimenting with various ajax and JSON options, I haven't been able to achieve the desired results. What I'm looking for is a simple data request that appen ...

Guide on using jQuery to update data in a form upon submission

Below is the form code: <div id="myForm"> <form method="post" id="contact-form" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> <div class="row uniform"> <div class="6u 12u$(medium)"&g ...

Ways to retrieve a single variable periodically and refresh it at intervals

One common issue faced by maintenance employees at my company is losing their log entry if they receive a call or text while filling out the daily form on their phones. To solve this problem, I came up with a solution to store the form values in PHP SESSIO ...

What is the best way to convert a 2D PHP array into a JavaScript array?

I have encountered a problem with a PHP array setup as follows: $output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3)); When I encoded the array to JSON, I received this output: $output = {"1":[1,1,1,1],"2":[2,2,2,2],"3":[3,3,3,3]} My goal is to ...

Using Vue js to scrollIntoView will only affect the specific element's div

I am currently working on a Vue page that consists of two divs. The Select-Div contains a list of elements, and when I click on an element from the list, the Scroll-Div is supposed to scroll to the corresponding ID element inside it. Ideally, the scrolling ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

How can one create a form in AngularJS using ng-model and ng-repeat to dynamically populate data from a UI model description

Check out the JSFiddle link here: http://jsfiddle.net/vorburger/hyCTA/3/. It showcases an innovative "UI modeling" concept I came up with using AngularJS. The form is not directly coded in the HTML template; instead, it's controlled by uimodel JSON wh ...

Preventing click events with pointer-events property in CSS while still allowing scrolling

Is there a way to use pointer-events: none to disable click events on a specific container while still allowing scroll functionality and an overlay? You can view my fiddle here: https://jsfiddle.net/1eu6d3sq/1/ Currently, when I apply pointer-events: non ...

What steps can be taken to avoid a nodejs server from crashing due to unexpected data?

While I have a wealth of experience working with servers like nginx, apache, and jboss, I am relatively new to nodejs server (I was drawn in by its socket.io features). What puzzles me is that seemingly insignificant issues such as accessing object.MyPrope ...

The ajax form submit function does not have the capability to automatically post content

On this particular webpage, there is a visible form labeled form A which contains a submit button with a post action. <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> I am looking to cre ...

Difficulty Communicating Recapcha 2 with the PHP Script

I am currently testing the installation of reCaptcha 2 with server-side verification using a form with one input field. My process involves sending the reCaptcha response via Ajax to a PHP page for verification. While I am able to capture the information p ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

When attempting to print certain attributes, the Node.JS array unexpectedly becomes undefined

While attempting to print a specific attribute such as "Full time or part time" in the getEmployeesByStatus() function, I encountered an issue where it suddenly returns undefined even though the entire array prints when I try to display it. This problem ha ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

Is it possible to implement a while loop in React?

Issue: I am facing a challenge while attempting to generate an array of 4 elements from a list using a while loop, but it seems to result in an infinite loop. const [options, setOptions] = useState([]); const fetchElements = () => { while(options. ...

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

Activate a mouse click event based on user input in a Shiny

I am currently developing a shiny app that includes a plotly sunburst chart. Once I provide the correctly formatted dataframe, I need to interact with the sunburst chart by clicking on it to "drill-down." Is there a way to replicate this mouse click act ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...