Skip to content

Commit

Permalink
[fix] prop-types: fix case with destructuring and defualt param
Browse files Browse the repository at this point in the history
Fixes #2241
  • Loading branch information
golopot authored and ljharb committed Apr 20, 2019
1 parent 9fbd037 commit 861fdef
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/util/usedPropTypes.js
Expand Up @@ -316,16 +316,17 @@ module.exports = function usedPropTypesInstructions(context, components, utils)
break;
case 'ArrowFunctionExpression':
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'FunctionExpression': {
if (node.params.length === 0) {
break;
}
type = 'destructuring';
properties = node.params[0].properties;
if (inSetStateUpdater()) {
properties = node.params[1].properties;
}
const propParam = inSetStateUpdater() ? node.params[1] : node.params[0];
properties = propParam.type === 'AssignmentPattern'
? propParam.left.properties
: propParam.properties;
break;
}
case 'VariableDeclarator':
for (let i = 0, j = node.id.properties.length; i < j; i++) {
// let {props: {firstname}} = this
Expand Down Expand Up @@ -421,7 +422,13 @@ module.exports = function usedPropTypesInstructions(context, components, utils)
* FunctionDeclaration, or FunctionExpression
*/
function markDestructuredFunctionArgumentsAsUsed(node) {
const destructuring = node.params && node.params[0] && node.params[0].type === 'ObjectPattern';
const param = node.params && inSetStateUpdater() ? node.params[1] : node.params[0];

const destructuring = param && (
param.type === 'ObjectPattern' ||
param.type === 'AssignmentPattern' && param.left.type === 'ObjectPattern'
);

if (destructuring && (components.get(node) || components.get(node.parent))) {
markPropTypesAsUsed(node);
}
Expand Down
25 changes: 25 additions & 0 deletions tests/lib/rules/prop-types.js
Expand Up @@ -3393,6 +3393,16 @@ ruleTester.run('prop-types', rule, {
errors: [
{message: '\'bar\' is missing in props validation'}
]
}, {
code: [
'function SomeComponent({bar} = baz) {',
' function f({foo}) {}',
' return <div className={f()}>{bar}</div>;',
'}'
].join('\n'),
errors: [
{message: '\'bar\' is missing in props validation'}
]
}, {
code: [
'class Hello extends React.PureComponent {',
Expand Down Expand Up @@ -4226,6 +4236,21 @@ ruleTester.run('prop-types', rule, {
message: '\'bar\' is missing in props validation'
}]
},
{
code: `
class Foo extends React.Component {
setZoo() {
this.setState((state, {zoo}) => ({ zoo }));
}
render() {
return <div />;
}
}
`,
errors: [{
message: '\'zoo\' is missing in props validation'
}]
},
{
code: `
class Foo extends React.Component {
Expand Down

0 comments on commit 861fdef

Please sign in to comment.