DEV Community

Dieter
Dieter

Posted on

Vue composables with state

I'd like to share with you how we started using hooks with Provide and Inject. In our application, we have a lot of state we share over child components. We started doing this with global ref's and actions to update these ref's. The downside was that we were often in a state that we had to reset those global variables (navigating from and back).

We solved this by using provide and inject in the following manner:

const employeeInfoKey = Symbol('employeeInfo');

function provideEmployeeInfo() {
   provide(employeeInfoKey, employeeInfoContext());
}

function useEmployeeInfo() {
   return inject<ReturnType<typeof employeeInfoContext>(employeeInfoKey)!();
}

function employeeInfoContext() {
   // use global state/context here
   const employeeInfo = ref<EmployeeInfo>();

   return function useEmployeeInfo() {
      // reference other hooks here

      return {
         employeeInfo: computed(() => employeeInfo.value),
         setEmployeeInfo(newEmployeeInfo: EmployeeInfo) {
           employeeInfo.value = newEmployeeInfo;
         }
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

Provide will always give us a fresh instance of our context. Let me know what you think of this approach.

Top comments (0)