How can i reusable function with boolean state in class component

Viewed 91

i have 5 state with 5 function too.. the state value is

imgError: false, imgError2: false, imgError3: false, imgError4: false, imgError5: false,

and the function is

const erroImg = () => {
  this.setState({
    imgError: true,
  })
}

const erroImg2 = () => {
  this.setState({
    imgError2: true,
  })
}
const erroImg3 = () => {
  this.setState({
    imgError3: true,
  })
}
const erroImg4 = () => {
  this.setState({
    imgError4: true,
  })
}
const erroImg5 = () => {
  this.setState({
    imgError5: true,
  })
  console.log('tes')
}

the question is,, how can i use one function for change the five state ??

3 Answers

Use an array for the imgErrors in state instead, and make a function that returns a function that changes the appropriate index:

this.state = {
  imgErrors: new Array(5).fill(false)
};
const errorImg = (i) => () => {
  this.setState({
    imgErrors: this.state.imgErrors.map(
      (val, j) => j === i ? true : val
    )
  });
};

Then, for example, instead of

onerror={erroImg3}

you could do

onerror={errorImg(2)}

(keeping in mind the zero-indexed arrays)

You can change multiple state at once doing something like this:

const changeAllStates = () => {
    this.setState({ state1: true, state2: true, state3: false });
}
erroImg = (imgError) => {
    this.setState({
      [imgError]: true,
    },()=>{
        console.log(this.state.imgError1);
        console.log(this.state.imgError2);
        console.log(this.state.imgError3);
    })
  }

 render() {
  return <React.Fragment>
      <Button onClick={() => {this.erroImg("imgError1")}}>click here</Button>
      <Button onClick={() => {this.erroImg("imgError2")}}>click here</Button>
      <Button onClick={() => {this.erroImg("imgError3")}}>click here</Button>
  </React.Fragment>;
 }
Related