0

So I've create two composables in vue 3. Both composable depends on each other for certain values.

useAuth.js

// Global State
const state = reactive({
   isLoggedIn: false,
   authToken: ''
})

export function useAuth() {
  const { userData } = useProfile() // requires `userData` from `useProfile()`

  const output = () => {
    console.log('This is user data from useProfile:', userData)
  }
  return {
    ...toRefs(state),
    output,
  }
}

useProfile.js

// Global State
const state = reactive({
   userData: {},
})

export function useProfile() {
  const { isLoggedIn } = useAuth() // requires `isLoggedIn` state from `useAuth()`

  const output = () => {
    console.log('This is use login state from useAuth:', isLoggedIn)
  }
  return {
    ...toRefs(state),
    output,
  }
}

As you can see its a circular dependency, and when I run this code I get stack overflow message in browser console and the app crashes.

I was wondering, how to resolve such circular dependancy in vue 3 composables?

Update #1

I also tried extracting both composable into a third composable and tried using that in useAuth() and useProfile() but still facing the same issue.

useAuthProfile.js


export function useAuthProfile() {

  const auth = useAuth()
  const profile = useProfile()

  return {
    ...toRefs(auth),
    ...toRefs(profile),
  }
}
Faisal Khurshid
  • 1,869
  • 3
  • 21
  • 27
  • 1
    Extract both dependencies into a third composable and then import the new composable into userAuth and userProfile. – IVO GELOV Aug 02 '22 at 12:53
  • @IVOGELOV I actually tried that. I've updated my post with the solution I tried but it didn't work. Any idea why it could be? – Faisal Khurshid Aug 03 '22 at 07:15
  • If you are using the original `useAuth.js` and `useProfile.js` - they are still referencing each other. My suggestion was to remove this referencing and instead make each of them reference that 3rd new composable instead which will provide what each of the other 2 composables needs. – IVO GELOV Aug 03 '22 at 07:17
  • @IVOGELOV I see, so I really cannot have all `auth` and `profile` related functionality in two files only, and extracting the common functionality into a third module will be more confusing in my case. So I guess, I can create a single composable with all the functionality so there is no cross-file interdependency. – Faisal Khurshid Aug 03 '22 at 07:30
  • Yes, this seems right. – IVO GELOV Aug 03 '22 at 07:41

0 Answers0