0

I have a simple clear button in my render method

<Button onClick={this.clearFilters(data)}> CLEAR </Button>

that calls function that clears out a state

  clearFilters(data){
   if (!data || !this.state) {
     return;
   }

   const blankFilter = '';
    this.setState({
      filter: blankFilter });
}

But if I add the setState line I got a ton of warnings and it pretty well freezes up.

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount

How can I implement this in componentWillMount?

EvilEddie
  • 1,026
  • 2
  • 12
  • 23

2 Answers2

1

I would suggest you change this <Button onClick={this.clearFilters(data)}> CLEAR </Button> to <Button onClick={()=>{this.clearFilters(data)}}> CLEAR </Button>. I think your button onClick method is trying to execute the clearFilters function when it's rendering thus the error

E_K
  • 2,159
  • 23
  • 39
0

this.clearFilter(data) is being executed immediately; it's a function call. It's not happening when the user clicks.

Change it to <Button onClick={() => this.clearFilters(data)}> CLEAR </Button>

Furthermore, why are you wanting to do this in componentWillMount? Why not just set the state initially to what it is supposed to be? Something like...

constructor(props) {
  super(props);
  this.state = { ... };
}

Good luck!

Kabir Sarin
  • 18,092
  • 10
  • 50
  • 41