Skip to content

Commit

Permalink
Added invariant with component stack (in dev) for useRef without func…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
bvaughn committed Mar 10, 2018
1 parent 60efe32 commit b54f287
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
15 changes: 14 additions & 1 deletion packages/react-reconciler/src/ReactFiberBeginWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,20 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
}

function updateUseRef(current, workInProgress) {
const nextChildren = workInProgress.type.renderProp(
const renderProp = workInProgress.type.renderProp;
let componentStack = '';
if (__DEV__) {
componentStack =
ReactDebugCurrentFiber.getCurrentFiberStackAddendum() || '';
}
invariant(
typeof renderProp === 'function',
'useRef requires a render function but was given %s.%s',
renderProp === null ? 'null' : typeof renderProp,
componentStack,
);

const nextChildren = renderProp(
workInProgress.pendingProps,
workInProgress.ref,
);
Expand Down
31 changes: 30 additions & 1 deletion packages/react/src/__tests__/useRef-test.internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ describe('useRef', () => {
let ReactFeatureFlags;
let ReactNoop;

function normalizeCodeLocInfo(str) {
return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
}

beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
Expand Down Expand Up @@ -159,7 +163,7 @@ describe('useRef', () => {
expect(ref.value).toBe(null);
});

it('should error if not provided a callback', () => {
it('should warn if not provided a callback during creation', () => {
expect(() => React.useRef(undefined)).toWarnDev(
'useRef requires a render function but was given undefined.',
);
Expand All @@ -170,4 +174,29 @@ describe('useRef', () => {
'useRef requires a render function but was given string.',
);
});

it('should error with a callstack if rendered without a function', () => {
let RefForwardingComponent;
expect(() => {
RefForwardingComponent = React.useRef();
}).toWarnDev('useRef requires a render function but was given undefined.');

ReactNoop.render(
<div>
<RefForwardingComponent />
</div>,
);

let caughtError;
try {
ReactNoop.flush();
} catch (error) {
caughtError = error;
}
expect(caughtError).toBeDefined();
expect(normalizeCodeLocInfo(caughtError.message)).toBe(
'useRef requires a render function but was given undefined.' +
(__DEV__ ? '\n in div (at **)' : ''),
);
});
});

0 comments on commit b54f287

Please sign in to comment.