[Vuejs]-Vue3 async composable export not reactive

1👍

the value for toRef is not available because at the time of initialization at toRef(navs.main) it has already been unresponsive otherwise useNavigation always returns Promise so either you have to use <script setup async> or skip the startup state like this:

// composables/useNavigation.js

// global variable for shared state
const navs = reactive({
  main: false,
  footer: false,
})

export const useNavigation = () => {
  const runTimeConfig = useRuntimeConfig()
  const endpointMenus = `${runTimeConfig.public.API_URL}/wp-api-menus/v2/menus`

  async function init() {
    const { data: menus, pending, error } = await useFetch(endpointMenus)

    Object.keys(navs).forEach(async (key) => {
      const menuID = menus.value.find((m) => m.slug === key)?.ID
      const endpointMenu = `${runTimeConfig.public.API_URL}/wp-api-menus/v2/menus/${menuID}`
      const { data: menu } = await useFetch(endpointMenu)
      navs[key] = menu.value

      console.log('navs.value: ', toRaw(navs))
    })
  }

  void init()

  return {
    ...toRefs(navs),
    test: computed(() => navs.main)
  }
}

Leave a comment