Skip to content

Commit

Permalink
fix(PropertiesPanel): only call callbacks once on first render
Browse files Browse the repository at this point in the history
  • Loading branch information
marstamm committed Mar 16, 2023
1 parent db25f49 commit 6209328
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
37 changes: 31 additions & 6 deletions src/PropertiesPanel.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {
useState,
useEffect
useEffect,
useMemo,
useRef
} from 'preact/hooks';

import {
Expand Down Expand Up @@ -120,7 +122,7 @@ export default function PropertiesPanel(props) {
const [ layout, setLayout ] = useState(createLayout(layoutConfig));

// react to external changes in the layout config
useEffect(() => {
useUpdateEffect(() => {
const newLayout = createLayout(layoutConfig);

setLayout(newLayout);
Expand Down Expand Up @@ -150,11 +152,14 @@ export default function PropertiesPanel(props) {
};

// set-up description context
const description = createDescriptionContext(descriptionConfig);
const description = useMemo(() => createDescriptionContext(descriptionConfig), [ descriptionConfig ]);

useEffect(() => {
if (typeof descriptionLoaded === 'function') {
descriptionLoaded(description);
}
}, [ description, descriptionLoaded ]);

if (typeof descriptionLoaded === 'function') {
descriptionLoaded(description);
}

const getDescriptionForId = (id, element) => {
return description[id] && description[id](element);
Expand Down Expand Up @@ -248,4 +253,24 @@ function createDescriptionContext(overrides) {
...DEFAULT_DESCRIPTION,
...overrides
};
}

// hooks //////////////////

/**
* This hook behaves like useEffect, but does not trigger on the first render.
*
* @param {Function} effect
* @param {Array} deps
*/
function useUpdateEffect(effect, deps) {
const isMounted = useRef(false);

useEffect(() => {
if (isMounted.current) {
return effect();
} else {
isMounted.current = true;
}
}, deps);
}
3 changes: 3 additions & 0 deletions test/spec/PropertiesPanel.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ describe('<PropertiesPanel>', function() {
});

// then
expect(layoutChangedSpy).to.have.been.calledOnce;
expect(layoutChangedSpy).to.have.been.calledWith(layoutConfig);
});

Expand Down Expand Up @@ -375,6 +376,7 @@ describe('<PropertiesPanel>', function() {
});

// then
expect(descriptionLoadedSpy).to.have.been.calledOnce;
expect(descriptionLoadedSpy).to.have.been.calledWith(descriptionConfig);
});

Expand All @@ -392,6 +394,7 @@ describe('<PropertiesPanel>', function() {
});

// then
expect(descriptionLoadedSpy).to.have.been.calledOnce;
expect(descriptionLoadedSpy).to.have.been.calledWith({});
});

Expand Down

0 comments on commit 6209328

Please sign in to comment.