Skip to content

Commit

Permalink
load import source in effect
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorshea committed Feb 28, 2022
1 parent 3f8803e commit 0eba8f9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
9 changes: 2 additions & 7 deletions src/client/packages/idom-client-react/src/components.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ReactDOM from "react-dom";
import htm from "htm";

import { useJsonPatchCallback } from "./json-patch.js";
import { loadModelImportSource } from "./import-source.js";
import { useImportSource } from "./import-source.js";
import {
createElementAttributes,
createElementChildren,
Expand Down Expand Up @@ -101,14 +101,9 @@ function ImportedElement({ model }) {
const layoutContext = React.useContext(LayoutContext);

const importSourceFallback = model.importSource.fallback;
const [importSource, setImportSource] = React.useState(null);
const importSource = useImportSource(model.importSource);

if (!importSource) {
// load the import source in the background
loadModelImportSource(layoutContext, model.importSource).then(
setImportSource
);

// display a fallback if one was given
if (!importSourceFallback) {
return html`<div />`;
Expand Down
25 changes: 24 additions & 1 deletion src/client/packages/idom-client-react/src/import-source.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
import React from "react";

import {
createElementAttributes,
createElementChildren,
} from "./element-utils.js";

export function loadModelImportSource(layoutContext, importSource) {
export function useImportSource(importSource) {
const layoutContext = React.useContext(LayoutContext);
const [importSource, setImportSource] = React.useState(null);

useEffect(() => {
let unmounted = false;

loadModelImportSource(layoutContext, model.importSource).then((src) => {
if (!unmounted) {
setImportSource(src);
}
});

return () => {
unmounted = true;
};
}, [layoutContext, model.importSource, setImportSource]);

return importSource;
}

function loadModelImportSource(layoutContext, importSource) {
return layoutContext
.loadImportSource(importSource.source, importSource.sourceType)
.then((module) => {
Expand Down

0 comments on commit 0eba8f9

Please sign in to comment.