Skip to content

Commit

Permalink
DevTools: Use cache reset API to clear cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Vaughn committed Jul 8, 2021
1 parent 51114a8 commit 14b8286
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
*/

import * as React from 'react';
import {useCallback, useContext} from 'react';
import {
useCallback,
useContext,
unstable_useCacheRefresh as useCacheRefresh,
} from 'react';
import ErrorBoundary from '../ErrorBoundary';
import {TreeStateContext} from './TreeContext';
import {StoreContext} from '../context';
import {getClearElementCallback} from '../../../inspectedElementCache';
import {clearCacheBecauseOfError} from '../../../inspectedElementCache';
import styles from './InspectedElementErrorBoundary.css';

type WrapperProps = {|
Expand All @@ -26,22 +29,10 @@ export default function InspectedElementErrorBoundaryWrapper({
// This seems best since an error inspecting one element isn't likely to be relevant to another element.
const {selectedElementID} = useContext(TreeStateContext);

// Note that getClearElementCallback(), like useContext(), must be called during render.
const store = useContext(StoreContext);
const selectedElement =
selectedElementID !== null ? store.getElementByID(selectedElementID) : null;
const clearElementCallback = useCallback(
() =>
selectedElement !== null
? getClearElementCallback(selectedElement)
: null,
[selectedElement],
);
const refresh = useCacheRefresh();
const handleDsmiss = useCallback(() => {
if (clearElementCallback !== null) {
clearElementCallback();
}
}, [clearElementCallback]);
clearCacheBecauseOfError(refresh);
}, [refresh]);

return (
<div className={styles.Wrapper}>
Expand Down
20 changes: 7 additions & 13 deletions packages/react-devtools-shared/src/inspectedElementCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,6 @@ function getRecordMap(): WeakMap<Element, Record<InspectedElementFrontend>> {
return getCacheForType(createMap);
}

/**
* Removes inspected element metadata from the cache.
*
* This function should only be called during render (since it reads from Context)
* and the callback it returns should be called prior to render.
*/
export function getClearElementCallback(element: Element): () => void {
const map = getRecordMap();
return function clearElementCallback(): void {
map.delete(element);
};
}

function createCacheSeed(
element: Element,
inspectedElement: InspectedElementFrontend,
Expand Down Expand Up @@ -203,3 +190,10 @@ export function checkForUpdate({
);
}
}

export function clearCacheBecauseOfError(refresh: RefreshFunction): void {
startTransition(() => {
const map = createMap();
refresh(createMap, map);
});
}

0 comments on commit 14b8286

Please sign in to comment.