vue.jsvuejs3

How to check if function is executed in setup context (composition API)


I have a function that is used in different contexts in the application. I use the composition API with script setup and Single File Components.

function useState() {
    const randomIntNum = randomInt() // returns for example 12307
    const state = ref(randomIntNum)
    if (IN_SETUP) provide("myState-" + randomIntNum, state)
    return { state }
}

It is sometimes executed directly in the setup method, like this:

// SingleStateDisplay.vue
<script setup>
// in setup()
const { state } = useState()
</script>

But sometimes not in setup(), like this:

// ListStateDisplay.vue
<script setup>
const buttonStates = [ref(0)] // rendered as list of numbers and modified one by one.

// bound to a button in the component template
function randomButtonClicked() {
    // not in setup()
    const { state: newState } = useState()
    buttonStates.push(newState)
}
</script>

My question now is, how can I get the value of IN_SETUP? Is there a simple way to check if we are currently in the setup() method context or not in Vue 3? If so, how?


Solution

  • For stateful components only, it is:

    if (getCurrentInstance()?.proxy)
      ...
    

    For any components, including functional ones:

    if (getCurrentInstance())
      ...
    

    It makes sense if a composable is allowed to be used in global scope outside a component. This looks like XY problem in this case because the use of useState inside randomButtonClicked is incorrect. useState can be refactored to extract randomInt() to a new function that can be used in random context. In this case the mentioned method of detection can be used to produce a warning in dev mode.