Mario Klisanic
Mario Klisanic

Reputation: 607

Vuex action payload is undefined

I have a component that looks like this(simplified):

<script>
import { mapActions } from 'vuex';
import router from '@/router';
import { bindingService } from '@/_services/binding.service';

export default {
    props: {
        serialNumber: { type: String, default: ' ' }
    },
    data: () => ({
        subscriptions: ['Loading...'],
        vin: null,
    }),
    computed: {
        splittedSerialNumber() {
            return this.serialNumber.split(' ')[0];
        }
    },
    created() {
        //fetch some data
        bindingService.fetchSomeData('xxx').then((data) => {
            this.vin = data;
        });        
    },
    methods: {
        ...mapActions('binding', ['setDeviceSerialNumber', 'setVehicleIdentificationNumber']),
        cancel() {
            router.push('/home');
        },
        ok() {
            console.log(this.vin);  //this console.log outputs valid data
            this.setVehicleIdentificationNumber(this.vin);
        },

    },
};
</script>

Then I have my store that look like this(simplified):

const state = {
    vehicleIdentificationNumber: null,
};

const actions = {
  setVehicleIdentificationNumber({ commit }, { vin }) {
        console.log(vin); // this console.log outputs undefined
        commit('SET_VEHICLE_IDENTIFICATION_NUMBER', vin);
    }
};

const mutations = {
SET_VEHICLE_IDENTIFICATION_NUMBER(state, vin) {
        state.vehicleIdentificationNumber = vin;
    },
};

const binding = {
    namespaced: true,
    state,
    actions,
    mutations,
};

export default binding;

I'm even more confused because I've been using pretty much the same format of actions and mutations in this project and they work. I'm out of ideas and looking forward to any kind of input :)

Upvotes: 1

Views: 2906

Answers (3)

Max S.
Max S.

Reputation: 1461

You should pass the data to the action like this:

actions: {
    myAction( store, payload = {myCustomKey: 'my value 1'} ){
        store.commit('myCustomMutation', payload.myCustomKey);
    }
}

And later уоu can call the action with or without the data:

this.$store.dispatch('myAction');
this.$store.dispatch('myAction', 'my value 2');

Upvotes: 0

Avocado
Avocado

Reputation: 901

In your setVehicleIdentificationNumber method on the component, you are passing in the vin as an integer argument.

In the action, the param is an object: { vin }.

Change the action param to vin, or pass in an object in the component: { vin: this.vin }

Upvotes: 3

Ohgodwhy
Ohgodwhy

Reputation: 50767

I think the problem here is that your vin property isn't reactive because you initialized it with a null value, but you're changing it to an object. Try this:

bindingService.fetchSomeData('xxx').then((data) => {
   Vue.set(this, 'vin', data)
});

Of course, you'll need to import Vue from 'vue'

Upvotes: 0

Related Questions