Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

addClass and removeClass implementation should be consistent across all components #793

Closed
moog16 opened this issue Apr 2, 2019 · 4 comments
Labels
Unresolved (Archived) Open and unresolved issues and PRs that were closed due to archiving the repository.

Comments

@moog16
Copy link

moog16 commented Apr 2, 2019

There are currently 2 different implementations of removeClass:

      removeClass: (className: string) => {
        const classList = new Set(this.state.classList);
        classList.delete(className);
        this.setState({classList});
      },

AND

      removeClass: (className: string) => {
        const {classList} = this.state;
        classList.delete(className);
        this.setState({classList});
      },

The difference being creating a new Set(). We should not be altering state directly, which is why we create new Set. addClass should also follow this pattern.

Related https://github.com/material-components/material-components-web-react/pull/792/files#r271249191

@ghost
Copy link

ghost commented Apr 2, 2019

To avoid mutating the current state and possible async issues I would write it like:

removeClass: (className: string) => {
  this.setState((prevState) => {
    const classList = new Set(prevState.classList);
    classList.delete(className);
    return {classList};
  });
}

Same for addClass, like you mentioned.

@moog16
Copy link
Author

moog16 commented Apr 2, 2019

Ya we have that in some places. What is the benefit of that syntax vs

removeClass: (className: string) => {
        const classList = new Set(this.state.classList);
        classList.delete(className);
        this.setState({classList});
      },

@ghost
Copy link

ghost commented Apr 2, 2019

It avoids the problems that arise from how react batches state updates. For example if removeClass is called twice in a row only the last call would have an affect, since it would override the first.

In my example, the previous state is taken into consideration. A better name for that variable in this scenario could be currentState.

@moog16
Copy link
Author

moog16 commented Apr 10, 2019

FYI - I just ran into this issue in the enhanced select (which I'm currently implementing). It happens on the foundation.handleBlur call, where removeClass is called twice. This fixed it!

@asyncLiz asyncLiz added the Unresolved (Archived) Open and unresolved issues and PRs that were closed due to archiving the repository. label Jan 14, 2025
@asyncLiz asyncLiz closed this as not planned Won't fix, can't repro, duplicate, stale Jan 14, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Unresolved (Archived) Open and unresolved issues and PRs that were closed due to archiving the repository.
Projects
None yet
Development

No branches or pull requests

2 participants