How do I access composable state from a module?

I am trying to pass state value of number from one store to another, why it isn’t working? Getting number is not defined.

import {
  reactive,
  toRefs
} from 'vue';
  
const state = reactive({
  number: 12
})

export function test() {
  
  return {
    ...toRefs(state)
  }
}

to this:

import {
  reactive,
  toRefs,
} from 'vue';

import { test } from '@/myvuex/somestore';

const state = reactive({
  testValue: 5
})

export function useGlobal() {

  console.log(number)

  return {
    ...toRefs(state),
    test,
    number
  }
}

Answer

The test import is a function, so it has to be called. It returns an object containing the refs of the first module’s state.

Then you can pass on the object’s number property:

const importedState = test();         // retrieving the state from module #1
const number = importedState.number;  // the `number` ref
    
export function useGlobal() {
  console.log(number.value);          // It's a ref now, use `.value`
      
  return {
    ...toRefs(state),
    test,
    number
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *