Skip to content

Consider adding a lint rule to check for using this.state after calling setState() #6192

@markerikson

Description

@markerikson

One of the most frequent errors we see asked about in Reactiflux is when a user writes code like this:

this.setState({data : 123});
console.log(this.state.data);
// Why isn't it "123" right now?

The issue is that new users haven't yet internalized that setState() is usually async, and so this.state is still the previous value when the log statement executes synchronously.

Would it be worth adding a lint rule that specifically checks for accesses of this.state after a call to this.setState(), and warns about it?

The lint rule might need to be scoped some to avoid false positives, such as only looking for uses of console.log() instead of any state access in general, or only looking for attempts to use specific fields that were referenced in setState or the entire state object.

The eslint-plugin-react/no-access-state-in-setstate rule might be a starting point for trying to write such a rule.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions