Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the state with React TypeScript 2.0?

For such a small component created by React and TypeScript.

interface Props {
}

interface State {
  isOpen: boolean;
}

class App extends React.Component<Props, State> {

  constructor(props: Props) {
    super(props);
    this.state = { 
      isOpen: false
    };
  }

  private someHandler() {
    // I just want to turn on the flag. but compiler error occurs.
    this.state.isOpen = true;
    this.setState(this.state);
  }

}

When I tried to upgrade TypeScript 1.8 to 2.0, then I got the compiler error like below.

error TS2540: Cannot assign to 'isOpen' because it is a constant or a read-only property.

I guess maybe it caused by this change.

  • https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-getters-without-setters-not-considered-read-only

so I just want to turn on the flag.

What should I do? Does anyone know the workaround?

Thanks.

update

the quick workaround is just doing like the below.

this.setState({ isOpen: true });
like image 427
mitsuruog Avatar asked Mar 09 '23 09:03

mitsuruog


1 Answers

The way that you are doing it would be a problem even without typescript. This line specifically is a issue.

this.state.isOpen = true;

This line of code is attempting to mutate state directly which is not the react way of doing things and precisely what typescript is trying to enforce.

One way to work with changing state, is by making a copy of the state which in your case would look like this;

let state = Object.assign({}, this.state)
state.isOpen = true;

Now you have a copy of state and when changing your local variable you are not changing state.

like image 105
Chaim Friedman Avatar answered Mar 11 '23 13:03

Chaim Friedman