From 3c6d571c8c942d5b747c37f61f8d99dc796e7ed2 Mon Sep 17 00:00:00 2001 From: Joshua Stiefer Date: Sat, 18 Nov 2017 12:15:32 -0700 Subject: [PATCH] Fix crash in no-unused-prop-types When checking props in setState updater functions, some assumptions were being made about the props argument being defined. --- lib/rules/no-unused-prop-types.js | 4 +-- tests/lib/rules/no-unused-prop-types.js | 40 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/lib/rules/no-unused-prop-types.js b/lib/rules/no-unused-prop-types.js index 846faa54df..f0c85596a6 100644 --- a/lib/rules/no-unused-prop-types.js +++ b/lib/rules/no-unused-prop-types.js @@ -134,7 +134,7 @@ module.exports = { // Make sure we are in the updater not the callback && scope.block.parent.arguments[0].start === scope.block.start && scope.block.parent.arguments[0].params - && scope.block.parent.arguments[0].params.length > 0 + && scope.block.parent.arguments[0].params.length > 1 ) { return scope.block.parent.arguments[0].params[1].name === node.object.name; } @@ -949,7 +949,7 @@ module.exports = { } function handleSetStateUpdater(node) { - if (!node.params || !node.params.length || !inSetStateUpdater()) { + if (!node.params || node.params.length < 2 || !inSetStateUpdater()) { return; } markPropTypesAsUsed(node); diff --git a/tests/lib/rules/no-unused-prop-types.js b/tests/lib/rules/no-unused-prop-types.js index 7321ff3afc..d4427aabc8 100644 --- a/tests/lib/rules/no-unused-prop-types.js +++ b/tests/lib/rules/no-unused-prop-types.js @@ -2197,6 +2197,46 @@ ruleTester.run('no-unused-prop-types', rule, { ].join('\n'), parser: 'babel-eslint', options: [{skipShapeProps: false}] + }, { + // issue #1542 + code: [ + 'class MyComponent extends React.Component {', + ' onFoo() {', + ' this.setState((prevState) => {', + ' this.props.doSomething();', + ' });', + ' }', + ' render() {', + ' return (', + '
Test
', + ' );', + ' }', + '}', + 'MyComponent.propTypes = {', + ' doSomething: PropTypes.func', + '};' + ].join('\n'), + options: [{skipShapeProps: false}] + }, { + // issue #1542 + code: [ + 'class MyComponent extends React.Component {', + ' onFoo() {', + ' this.setState(({ something }) => {', + ' this.props.doSomething();', + ' });', + ' }', + ' render() {', + ' return (', + '
Test
', + ' );', + ' }', + '}', + 'MyComponent.propTypes = {', + ' doSomething: PropTypes.func', + '};' + ].join('\n'), + options: [{skipShapeProps: false}] }, { // issue #106 code: `