Search code examples
vue.jsvuejs2vuexvuex-modules

data sent with vuex action return undefined


i'm using axios with vuex, i need to send data with json form to execute post request and add new row with axios, i'm using vuex, when action is trigered it doesn't keep the data and sent it on action, the data json is created on vue componment but don't send it to action to execute axios post :

Action.js:

export const addClassification = ({data}) => {
    console.log('data actio:', {data})
    axios
    .post("/vendor/classification/save", data, {
        headers: {
            "Content-Type": "application/json",
            //  withCredentials: true //sent with cookie
            Authorization: "Bearer " + Vue.$cookies.get("jwt"),
        }
    })
    .then((res) => {
        console.log('res', res)
        // commit("ADD_TO_CLASSIFICATION", data);
    })
    .catch((err) => {
        console.log(err);
    });

state.js:

export default {
    vendorClassificationList: [],
}

page.vue:

<BaseButton
    label="Modifier"
    classValue="btn-outline-primary"
    @click.native="addClassificationData"
/>
data() {
    return {
        submitStatus: "",
        name: this.$route.params.name,
        id: this.$route.params.id,
        code: this.$route.params.code,
        jsonData:[]
    };
},
methods: {
    ...mapActions(["addClassification"]),
    addClassificationData() {
        this.jsonData = JSON.stringify({
            id: null,
            name: this.name,
            code:this.code,
            active:true
        })
        console.log('json is', this.jsonData)
        this.addClassification({
            data : this.jsonData
        })
    },

Solution

  • Actions is Vuex receive the vuex context as the first param, as you can see in the docs.

    In other words if you change in Action.js:

    addClassification = ( {data}) => {

    to

    addClassification = (vuexContext, {data}) => {

    it should do the trick. You can call the param vuexContext, context, destructure it if needed or call it _ if unused (as in your case), doesn't really matter, as long as it's there.