D
D
dron1122021-02-13 14:36:04
Vue.js
dron112, 2021-02-13 14:36:04

How to set initialState in Vuex?

1) In mounted I do a dispatch action that should receive data from firebase
2) As soon as it receives it, I commit mutations and put this data in state

The problem is that in devTools (Vue), initialState = received data from the server, although the commit mutation that should bring this data into the state goes below.
6027b9965928a963743966.png

Component

export default {
    name: 'Home',
    components: {
        Footer, Card, Header
    },
    beforeMount() {
      this.$store.commit('getInitialState', {
        name: '',
        avatar: '',
        fetchDataUser: false
      })
    },
    mounted() {
      this.$store.dispatch('getFlatsAction')
      this.$store.dispatch('getInfoUser')
    },
    computed: {
        getFlats() {
            return this.$store.state.flats.items
        }
    },
    methods: {
        favoriteHandler(id) {
            this.$store.commit('addFavorites', id)
        }
    }
}
</script>


store
const state = {
    admin: {
        name: '',
        avatar: '',
        fetchDataUser: false
    }
}

const actions = {
    async getInfoUser(cxt) {
        cxt.commit('getStartDataUser', {
            name: '',
            avatar: '',
            fetchDataUser: false
        })
        try{
            const response = await fetch('https://houses-881f7-default-rtdb.firebaseio.com/users/admin.json')
            const data = await response.json()

            cxt.commit('getSuccessDataUser', data)

            // if(!cxt.state.admin.fetchDataUser) {
            //     cxt.commit('saveDataAdminLocalStore', data)
            // }
        } catch (e) {
            cxt.commit('getFailureDataUser', e)
        }
    }
}
const mutations = {
getSuccessDataUser(state, payload) {
        state.admin.name = payload.name
        state.admin.avatar = payload.avatar
        state.admin.fetchDataUser = true
    },
}
}


From my observations
1) if I make the Internet speed lower, then the state is set correctly
, I assume that this is due to the fact that with a slow Internet, mouted() comes later and therefore data from the server arrives later, but why doesn’t it work for me at normal speed I don't understand

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question