Skip to content

Commit 74a9522

Browse files
committed
[Fix] destructuring-assignment: do not force destructuring of optionally chained properties
Fixes #3520
1 parent 161e5a8 commit 74a9522

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
77

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

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

1315
## [7.32.0] - 2023.01.10

lib/rules/destructuring-assignment.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ module.exports = {
137137
|| (contextName && node.object.name === contextName)
138138
)
139139
&& !isAssignmentLHS(node);
140-
if (isPropUsed && configuration === 'always') {
140+
if (isPropUsed && configuration === 'always' && !node.optional) {
141141
report(context, messages.useDestructAssignment, 'useDestructAssignment', {
142142
node,
143143
data: {
@@ -149,7 +149,10 @@ module.exports = {
149149
// const foo = useContext(aContext);
150150
// foo.aProp
151151
const isContextUsed = contextSet.has(node.object.name) && !isAssignmentLHS(node);
152-
if (isContextUsed && configuration === 'always') {
152+
const optional = node.optional
153+
// the below is for the old typescript-eslint parser
154+
|| context.getSourceCode().getText(node).slice(node.object.range[1] - node.range[0], node.object.range[1] - node.range[0] + 1) === '?';
155+
if (isContextUsed && configuration === 'always' && !optional) {
153156
report(context, messages.useDestructAssignment, 'useDestructAssignment', {
154157
node,
155158
data: {

tests/lib/rules/destructuring-assignment.js

+11
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,17 @@ ruleTester.run('destructuring-assignment', rule, {
422422
options: ['never'],
423423
settings: { react: { version: '16.8.999' } },
424424
},
425+
{
426+
code: `
427+
import { useContext } from 'react';
428+
429+
const MyComponent = (props) => {
430+
const foo = useContext(aContext);
431+
return <div>{foo?.test}</div>
432+
};
433+
`,
434+
features: ['optional chaining'],
435+
},
425436
]),
426437

427438
invalid: parsers.all([].concat(

0 commit comments

Comments
 (0)