Search code examples
vuejs3inertiajspinia

Reference value returns null after initialization pinia vue3


I have the following code:

import {UseBaseStore} from "@/Stores/UseBaseStore.js";
import {UseBalanceStore} from "@/Stores/UseBalanceStore.js";

const props = defineProps({
    'balance': Object
})

const baseStore = UseBaseStore()
baseStore.setBalance(props.balance)
baseStore.init()

I initialize a basestore that i want to use for initialization to prevent duplicate code but i run into a problem. With the following code:

import {defineStore} from "pinia";
import {ref} from "vue";
export const UseBaseStore = defineStore('BaseStore', () => {
    const balance = ref(null)

    function setBalance(balance) {
        balance.value = balance
        console.log(balance.value)
    }

    function init() {
        console.log(balance.value)
    }

    return {balance, setBalance, init}
})

The first console.log returns a proper object as expected but the second returns null, does anyone know why?


Solution

  • It's an issue related to precedence and scope. Your function is assigning to the function parameter named balance, and not the store variable named balance. To correct the issue, give the parameter a different name

    const balance = ref(null)
    
    function setBalance(newBalance) {
      balance.value = newBalance
      console.log(balance.value)
    }