Skip to content

Commit

Permalink
Added initialized value to useViewModel
Browse files Browse the repository at this point in the history
  • Loading branch information
gius committed Jul 26, 2023
1 parent 5b5cf59 commit 0a6acd2
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 10 deletions.
2 changes: 1 addition & 1 deletion examples/navigation/src/settings/Settings.tsx
Expand Up @@ -4,7 +4,7 @@ import React from "react";
import SettingsViewModel from "./settingsViewModel";

export function Settings() {
const vm = useViewModel(() => new SettingsViewModel(), {}, []);
const { vm } = useViewModel(() => new SettingsViewModel(), {}, []);

return (
<p>
Expand Down
11 changes: 4 additions & 7 deletions packages/views/src/hooks/useViewModel.ts
@@ -1,26 +1,23 @@
"use client";

import type { DependencyList } from "react";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { ViewModelLifecycleManager } from "../helpers/viewModelLifecycleManager";
import type { IViewModel } from "../types";
import { ManualPromise } from "@frui.ts/helpers";

export function useViewModel<TContext, TViewModel extends IViewModel<TContext>>(
factory: () => TViewModel,
context: TContext,
dependencies?: DependencyList
) {
const vmManager = useRef(new ViewModelLifecycleManager(factory));
const initializedPromise = useRef(new ManualPromise<true>());
const [initialized, setInitialized] = useState(false);

const currentContext = useRef(context);
currentContext.current = context;

useEffect(() => {
void vmManager.current
.initialize(currentContext.current)
.then(() => initializedPromise.current.status === "new" && initializedPromise.current.resolve(true));
void vmManager.current.initialize(currentContext.current).then(() => setInitialized(true));

return () => {
void vmManager.current.close(currentContext.current);
Expand All @@ -31,5 +28,5 @@ export function useViewModel<TContext, TViewModel extends IViewModel<TContext>>(
void vmManager.current.navigate(currentContext.current);
}, dependencies ?? [context]);

return { vm: vmManager.current.instance, initialized: initializedPromise.current.promise };
return { vm: vmManager.current.instance, initialized };
}
4 changes: 2 additions & 2 deletions stories/package.json
Expand Up @@ -27,7 +27,7 @@
"react": "^18.2.0"
},
"scripts": {
"storybook": "cross-env NODE_OPTIONS=--openssl-legacy-provider storybook dev -p 6006",
"build-storybook": "cross-env NODE_OPTIONS=--openssl-legacy-provider storybook build"
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
}
}

0 comments on commit 0a6acd2

Please sign in to comment.