NuxtN
Nuxt2y ago
10 replies
Muhammad Awais

Handling multiple modals.

How can we handle multiple modals within the Nuxt app. I have separate modals for signup, login, password reset and some other things. But I'm unable to manage them globally. I have tried
useState
but it throws the error cannot stringify functions. Here are my implementations:
usemodal works as a controller for single modal
export const useModal = (closeOtherModals: () => void) => {
  const isOpen = ref(false);

  function open() {
    closeOtherModals();
    isOpen.value = true;
  }

  function close() {
    isOpen.value = false;
  }

  return {
    isOpen: computed(() => isOpen.value),
    open,
    close,
  };
};

define-modals defines all the modals available.
export default () => {
  const modals = useState(
    "modals",
    (): { [k: string]: ReturnType<typeof useModal> } => {
      return {};
    },
  );
  const closeModals = () => {
    let modal: keyof typeof modals.value;
    for (modal in modals.value) {
      if (modals.value[modal].isOpen.value) {
        modals.value[modal].close();
      }
    }
  };

  modals.value = {
    login: useModal(closeModals),
    signup: useModal(closeModals),
    forgotPassword: useModal(closeModals),
    resetPassword: useModal(closeModals),
    emailConfirmationSuccess: useModal(closeModals),
    emailConfirmationFailed: useModal(closeModals),
    bookingDetailsModal: useModal(closeModals),
    profileCompletionModal: useModal(closeModals),
  };
  return {
    loginModal: modals.value.login,
    signupModal: modals.value.signup,
    forgotPasswordModal: modals.value.forgotPassword,
    resetPasswordModal: modals.value.resetPassword,
    emailConfirmSuccessModal: modals.value.emailConfirmationSuccess,
    emailConfirmFailedModal: modals.value.emailConfirmationFailed,
    bookingDetailsModal: modals.value.bookingDetailsModal,
    profileCompletionModal: modals.value.profileCompletionModal,
  };
};

Inject/provide were not also helpful as state is not SSR friendly in that case.
Was this page helpful?