Skip to content

Commit

Permalink
Supporting async/await in no-did-mount-setstate rule (fixes jsx-esl…
Browse files Browse the repository at this point in the history
  • Loading branch information
idanen committed Sep 25, 2018
1 parent bd083bf commit e896417
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions docs/rules/no-did-mount-set-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ var Hello = createReactClass({
});
```

```jsx
var Hello = createReactClass({
componentDidMount: async function() {
const newName = await getName();
this.setState({
name: newName
});
},
render: function() {
return <div>Hello {this.state.name}</div>;
}
});
```

## Rule Options

```js
Expand Down
8 changes: 8 additions & 0 deletions lib/util/makeNoMethodSetStateRule.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ function makeNoMethodSetStateRule(methodName, shouldCheckUnsafeCb) {
return false;
}

function hasAsyncBefore(ancestor, callee) {
return context.getTokensBetween(context.getFirstToken(ancestor), callee)
.filter(token => token.value === 'await').length;
}

// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
Expand Down Expand Up @@ -69,6 +74,9 @@ function makeNoMethodSetStateRule(methodName, shouldCheckUnsafeCb) {
) {
continue;
}
if (ancestor.value.async && hasAsyncBefore(ancestor, callee)) {
continue;
}
context.report({
node: callee,
message: `Do not use setState in ${ancestor.key.name}`
Expand Down
30 changes: 30 additions & 0 deletions tests/lib/rules/no-did-mount-set-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ ruleTester.run('no-did-mount-set-state', rule, {
});
`,
parser: 'babel-eslint'
}, {
code: `
var Hello = createReactClass({
componentDidMount: async function() {
const data = await getFromServer(this.props);
this.setState({
data: data
});
}
});
`,
parser: 'babel-eslint'
}],

invalid: [{
Expand Down Expand Up @@ -225,5 +237,23 @@ ruleTester.run('no-did-mount-set-state', rule, {
errors: [{
message: 'Do not use setState in componentDidMount'
}]
}, {
code: `
var Hello = createReactClass({
componentDidMount: async function() {
this.setState({
loading: true
});
const data = await getFromServer(this.props);
this.setState({
loading: false,
data: data
});
}
});
`,
errors: [{
message: 'Do not use setState in componentDidMount'
}]
}]
});

0 comments on commit e896417

Please sign in to comment.