What is the process of setting a function as a property value in the Vuex State of an object from a component?

Can someone assist me with incorporating a function into the property of an object as a value for the state in my Vuex store?

I am currently restructuring some code for a website using vue.js and fullpage.js. I have moved my fullpage options to the vuex store, but I am facing difficulties adding a method to the onLeave callback in my options from a child component.

Initially, I had the options stored in the data object of the home component and passed a method from the same component.

data{
  return {
    options:{
      onLeave: this.morphScroll
    }
  }
},
methods: {
   morphScroll(origin, destination, direction){
     //do something
   }
}

The options now reside in the state, and I pass fullpage as a prop from the parent component (home) to the child component. If I directly assign the value by changing the state using

$store.state.fullpage.options.onLeave = function
, it functions correctly and I can see the assigned value in Vue DevTools.

However, when I attempt to make a change by dispatching an action instead, I end up with a value of undefined being assigned to onLeave... This occurs when dispatching from the beforeCreate lifecycle hook.

//Action dispatched
this.$store.dispatch('newFullPageOption', 'onLeave', onLeaveCallback)

 //Mutation to set the state
//where would be 'onLeave', val would be the function being passed
setNewFullpageOption(state, where, val){
  Vue.set(state.fullpage.options, where, val)
}

//My action
newFullPageOption(context, where, val){
    context.commit('setNewFullpageOption', where, val )
}
    
//Function I am passing to onLeave option
//It is being passed in the beforeCreate() lifecycle hook
const onLeaveCallback = (origin, destination, direction) => { 
if( origin.index == 0 && direction == 'down') {
  this.morphSVG.direction = 'normal'
  this.morphSVG.play()
  this.fpzindex = false
  console.log('scroll down destination:', destination.index)
}
if( origin.index == 1 && direction == 'up') {
  this.morphSVG.direction = 'reverse'
  this.morphSVG.play()
  this.fphidden = true
    console.log('scroll up destination:', destination.index)
  }
  console.log('data from component:', this.testdata)
}

//this.$store.dispatch('newFullPageOption', 'onLeave', onLeaveCallback)
this.$store.state.fullpage.options.onLeave = onLeaveCallback

Your assistance is highly appreciated. Thank you!

Answer №1

When working with actions and mutations, it's important to remember that they only take two arguments: the name and the payload. To pass multiple values, you can use an object as the payload.

this.$store.dispatch('newFullPageOption', {
   onLeave: 'onLeave',
   onLeaveCallback: onLeaveCallback
})

An alternative way to write this is by utilizing object property shorthand, where you still have just 2 arguments. The property names need to match existing variables with the same name:

const onLeave = 'onLeave';
this.$store.dispatch('newFullPageOption', { onleave, onLeaveCallback })

Within the action function, you receive two arguments: context and payload. The payload can be destructured, resembling object property shorthand in reverse:

NewFullpageOption(context, { onLeave, onLeaveCallback }){ // Destructuring
  // Mutations also follow the two-argument pattern:
  context.commit('setNewFullpageOption', { onLeave, onLeaveCallback })
}

Mutations adhere to the same structure of accepting two arguments:

setNewFullpageOption(state, { onLeave, onLeaveCallback }){
   Vue.set(state.fullpage.options, onLeave, onLeaveCallback)
}

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

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

I'm curious if it's possible to modularize a Page Element in Next.js that receives staticProps through a parsedUrlQuery

The scenario involves opening http://localhost:3000/users/101 Desired layout for the page and integration of the second code snippet in [id].tsx import CTASection from '../../components/samples/CTASection'; import { User } from "../../inte ...

I need help figuring out how to deactivate specific dates in vue-simple-calendar

Currently, I am incorporating vue-simple-calendar into my vue3 UI. As part of this implementation, I need to restrict access to both past and future weeks within the calendar view, ensuring that only the current week is enabled. I am curious if there is a ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

show me where Mongo has been installed

It's been a challenge for me to locate the installation path of Mongo in my Mint system. Is there a way to reveal the path for mongodb on Mint? I've attempted running the command mongodb v Unfortunately, this only provided the version informa ...

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

Install only the necessary components from React Material UI

Is it possible to selectively install specific components from React Material UI? Specifically interested in the Autocomplete component, which can be found at this link. ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

The basic Node.js API for greeting the world encountered a connection failure

I'm currently working on setting up a basic hello world route using nodejs and express. After running node index.js, I see listening on port 3000 in the console, but when I attempt to access http://localhost:3000/helloworld, it just keeps trying to co ...

Encountering a 404 error while using Node.js for app.get requests with Postgres as the

Currently, I am in the process of learning Node.js by following a tutorial that guides me on building a simple API. The tutorial utilizes a sample database for demonstration purposes, but I decided to use my own Postgres DB instead. However, when trying to ...

Progress bar status displayed while uploading multiple files

I'm currently working on a Django project where I have set up a page to input data information about a file and then upload the file itself. https://i.sstatic.net/jB5cr.png Whenever the user clicks on the 'More datasets' button, it dyna ...

Despite correctly declaring jquery-ui.js and numeric.js, the jQuery datepicker and numeric plugins are not working as expected

element, it's strange that I am not receiving any error messages. However, despite this, the jquery datepicker function and numeric plugin are not working on the intended input fields they are supposed to be linked to. This particular page is a simpl ...

Manage the material-ui slider using play and pause buttons in a React JS application

I have a ReactJS project where I am utilizing the continuous slider component from material-ui. My goal is to be able to control the slider's movement by clicking on a play button to start it and stop button to halt it. Below is the code snippet of th ...

Import JSON Data into Angular-nvD3 Chart (AngularJS)

I am seeking help to load encoded JSON Data retrieved from a database via queries into an Angular-nvD3 graph. I am unsure about the best approach to achieve this task. The encoded JSON data is fetched using API queries from a database table called PRODUCT ...

Importing a class from a JavaScript file in Typescript: a step-by-step guide

I need help with the following: Importing a js file that defines a class: ./myClass/index.js Declaring the public methods of MyClass (unsure of where to do this, whether in index.ts or another declaration file) Creating a typescript file that exposes the ...

Using Express Router to call a dynamic route instead of the intended named route

I'm currently developing an API using Express.js, implementing routes and controllers. Within my api.js file, I have the following setup: const app = express() app.use('/clients', clients) Then, in my router/client.js file, I specify the e ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

What's the best way to modify HTML element classes using Javascript?

I have designed a custom cms theme with various customization options that I wish to showcase in a live demo. My goal is to implement Javascript style switchers or modifiers where users can choose values from checkboxes or select tags, and see their select ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...