Skip to content

Commit

Permalink
feat: Show displayName for each context in React Developer Tools (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
zheeeng committed Mar 1, 2021
1 parent 6858b1c commit 6c1d5e0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
11 changes: 7 additions & 4 deletions src/index.tsx
Expand Up @@ -50,16 +50,19 @@ function constate<Props, Value, Selectors extends Selector<Value>[]>(
const contexts = [] as React.Context<any>[];
const hooks = ([] as unknown) as Hooks<Value, Selectors>;

const createContext = () => {
const createContext = (displayName: string) => {
const context = React.createContext(NO_PROVIDER);
if (isDev && displayName) {
context.displayName = displayName;
}
contexts.push(context);
hooks.push(createUseContext(context));
};

if (selectors.length) {
selectors.forEach(createContext);
selectors.forEach((selector) => createContext(selector.name));
} else {
createContext();
createContext(useValue.name);
}

const Provider: React.FC<Props> = ({ children, ...props }) => {
Expand All @@ -76,7 +79,7 @@ function constate<Props, Value, Selectors extends Selector<Value>[]>(
};

if (isDev && useValue.name) {
Provider.displayName = `${useValue.name}.Provider`;
Provider.displayName = "Constate";
}

return [Provider, ...hooks];
Expand Down
4 changes: 2 additions & 2 deletions test/index.test.tsx
Expand Up @@ -157,7 +157,7 @@ test("without provider", () => {

test("displayName with named useValue with no selector", () => {
const [Provider] = constate(useCounter);
expect(Provider.displayName).toBe("useCounter.Provider");
expect(Provider.displayName).toBe("Constate");
});

test("displayName with anonymous useValue", () => {
Expand All @@ -173,5 +173,5 @@ test("displayName with named useValue with selectors", () => {
// @ts-expect-error
(value) => value.increment
);
expect(Provider.displayName).toBe("useCounter.Provider");
expect(Provider.displayName).toBe("Constate");
});

0 comments on commit 6c1d5e0

Please sign in to comment.