Mark
Mark

Reputation: 169

Vuex store returns [__ob__: Observer] in created() method instead of string

I have a Vuex store that contains a username string. It's initially set to and empty string but every user, new or old, will be assigned a random string initially.

I want to allow users to change their username. I also want to display the username as the initial value in the text input.

However, the initial value is just an empty string. When logging username in created (or any lifecycle methods after), I get [__ob__: Observer]. If I set a timeout of 500ms, I get the expected string but this is too messy for me.

Here's the relevant code:

<template>
  <form @submit.prevent>
    <input
      type="text"
      v-model="usernameField"
    />
    <button @click="usernameUpdate()">
      Submit
    </button>
  </form>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator'
  import { namespace } from 'vuex-class'

  const AccountGetter = namespace('account').Getter
  const AccountAction = namespace('account').Action

  const AppProps = Vue.extend({
    data: () => {
      return {
        usernameField: ''
      }
    },
    created() {
      this.usernameField = this.username
      console.log(this.username)
      // returns [__ob__: Observer]
      // using setTimeout() works though
    },
    methods: {
      async usernameUpdate() {
        // working code using updateUserProfile
      }
    }
  })

  export default class VerifyGame extends AppProps {
    @AccountGetter username!: String;
    @AccountAction updateUserProfile
  }
</script>

Vuex store:

// also includes updateUserProfile mutation

import { AccountState, RootState } from './types'
import { GetterTree } from 'vuex'

type AccountGetter = GetterTree<AccountState, RootState>

export const state: AccountState = {
  username: ''
}

export const getters: AccountGetter = {
  username: state => state.username
}

Upvotes: 1

Views: 2425

Answers (1)

Sreenath C A
Sreenath C A

Reputation: 56

[ob: Observer] is an object. The value you need would be in a variable under it. You can get the desired variable by using this.username.varname.

I would recommend that you use something like below for your vuex. And use the addUserData mutation to update your username. The data in it can be accessed as this.$store.state.userData.username

export default new Vuex.Store({
    state: {
        userData: {
            username: ""
        }
    },
    getters: {},
    mutations: {
        addUserData(state, data) {
            // state.userData.assign(data)
            state.userData = Object.assign({}, data);
        }
    },
    actions: {}
});

Upvotes: 1

Related Questions