Skip to content

Commit

Permalink
[Fix] destructuring-assignment: do not force destructuring of optio…
Browse files Browse the repository at this point in the history
…nally chained properties

Fixes #3520
  • Loading branch information
ljharb committed Jan 16, 2023
1 parent 161e5a8 commit 74a9522
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -7,7 +7,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange

### Fixed
* prevent circular dependency in index and "all" config ([#3519][] @ljharb)
* [`destructuring-assignment`]: do not force destructuring of optionally chained properties ([#3520][] @ljharb)

[#3520]: https://github.com/jsx-eslint/eslint-plugin-react/issues/3520
[#3519]: https://github.com/jsx-eslint/eslint-plugin-react/issues/3519

## [7.32.0] - 2023.01.10
Expand Down
7 changes: 5 additions & 2 deletions lib/rules/destructuring-assignment.js
Expand Up @@ -137,7 +137,7 @@ module.exports = {
|| (contextName && node.object.name === contextName)
)
&& !isAssignmentLHS(node);
if (isPropUsed && configuration === 'always') {
if (isPropUsed && configuration === 'always' && !node.optional) {
report(context, messages.useDestructAssignment, 'useDestructAssignment', {
node,
data: {
Expand All @@ -149,7 +149,10 @@ module.exports = {
// const foo = useContext(aContext);
// foo.aProp
const isContextUsed = contextSet.has(node.object.name) && !isAssignmentLHS(node);
if (isContextUsed && configuration === 'always') {
const optional = node.optional
// the below is for the old typescript-eslint parser
|| context.getSourceCode().getText(node).slice(node.object.range[1] - node.range[0], node.object.range[1] - node.range[0] + 1) === '?';
if (isContextUsed && configuration === 'always' && !optional) {
report(context, messages.useDestructAssignment, 'useDestructAssignment', {
node,
data: {
Expand Down
11 changes: 11 additions & 0 deletions tests/lib/rules/destructuring-assignment.js
Expand Up @@ -422,6 +422,17 @@ ruleTester.run('destructuring-assignment', rule, {
options: ['never'],
settings: { react: { version: '16.8.999' } },
},
{
code: `
import { useContext } from 'react';
const MyComponent = (props) => {
const foo = useContext(aContext);
return <div>{foo?.test}</div>
};
`,
features: ['optional chaining'],
},
]),

invalid: parsers.all([].concat(
Expand Down

0 comments on commit 74a9522

Please sign in to comment.