moses's avatar
Level 2

How can I upload file using vuex store on the vue component?

If I using ajax in vue component like this :

<template>
    <div>
        ...
    </div>
</template>
<script>
    export default {
        methods: {
            submitForm() {
                ...
                formData.append('file', files)
                axios.post(this.baseUrl+'/member/profile/update',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                ).then(function(response) {
                    console.log('success')
                })
                .catch(function(error) {
                    console.log('fail')
                })
            }
        }
    }
</script>

It works. I successfully get the file

But here I want to using vuex store

My pattern of vuex store like this :

I change my vue component like this :

<template>
    <div>
        ...
    </div>
</template>
<script>
    export default {
        methods: {
            submitForm() {
                ...
                formData.append('file', files)
                this.updateProfile({formData, reload: true})
            }
        }
    }
</script>

In the component vue, it will call updateProfile method in modules user

The modules user like this :

import { set } from 'vue'
import users from '../../api/users'
import * as types from '../mutation-types'
// initial state
const state = {
    addStatus:null
}
// getters
const getters = {
    updateProfileStatus: state =>  state.addStatus,
}
// actions
const actions = {
    updateProfile ({ dispatch,commit,state },{user,reload})
    {
        users.updateProfile(user,
            response => {
                commit(types.UPDATE_PROFILE_SUCCESS)
            },
            errors => {
                commit(types.UPDATE_PROFILE_FAILURE)
            }
        )
    }
}
// mutations
const mutations = {
    [types.UPDATE_PROFILE_SUCCESS] (state){
        state.addStatus = 'success'
    },
    [types.UPDATE_PROFILE_FAILURE] (state){
        state.addStatus = 'failure'
    }
}
export default {
    state,
    getters,
    actions,
    mutations
}

From the modules user, it will call updateProfile method in api users

The api users like this :

import Vue from 'vue'
export default {

    updateProfile (user, cb, ecb = null) {
        axios.post('/member/profile/update', user)
            .then(response => cb(response))
            .catch(error => ecb(error))
    }
}

So my pattern like that. So i'm using pattern of vuex store

My problem here is I'm still confused to send file data

If I console.log(user) in the updateProfile method on modules user, the result is undefined

How can I send file data using vuex store?

0 likes
0 replies

Please or to participate in this conversation.