Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React from 'react';
// @ts-ignore
globalThis.whenCalledBy = function whenCalledBy(fnName: string, depth = Infinity) {
const [, , , ...stackTraceLines] = (new Error().stack ?? '')
.split('\n')
.map((line) => {
const matches = /^at (?<name>(?:\w+|<anonymous>)) ?/.exec(line.trim());
return matches ? matches.groups?.name : undefined;
})
.filter((stackLine): stackLine is string => stackLine !== undefined);
return (depth !== Infinity ? stackTraceLines.slice(0, depth) : stackTraceLines).some((fn) => fn === fnName);
};
// @ts-ignore
globalThis.whenRenderedWithin = function whenRenderedWithin(componentName: string, depth = Infinity) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const currentStack: string =
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDebugCurrentFrame.getCurrentStack() ?? '';
const [, ...componentStack] = currentStack
.split('\n')
.map((line) => {
const matches = /^at (?<name>\w+) ?/.exec(line.trim());
return matches ? matches.groups?.name : undefined;
})
.filter((stackLine): stackLine is string => stackLine !== undefined);
return (depth !== Infinity ? componentStack.slice(0, depth) : componentStack).some((cn) => cn === componentName);
};
@sebinsua
Copy link
Author

sebinsua commented Jun 20, 2022

We should probably be using this API in order to do things correctly. Potentially need to find out where the renderers come from?

It seems that we can get the ones which were setup in React Devtools using this line:

__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))

The renderers seem to be setup deep within this function.

Edit: Unfortunately react-devtools-shared isn't published therefore doing things this way seems impractical. Also, the implementation is more complicated and therefore more fragile to API changes (even more so than using the secret API!).

@sebinsua
Copy link
Author

sebinsua commented Jun 28, 2022

(Another idea that might be interesting is a set of assertions which both operate as TypeScript checks but also in development mode can call debugger.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment