I would like to create a switch between tabs based on a boolean array. However, I do not know how to replace the switchTabs function to stop this error from being displayed. The interface is built like this:
interface IData {
setData: boolean[];
}
My constructor looks like this:
constructor(props: IData) {
super(props);
this.state = {
setData: [true, false, false]
}
}
However, the method in which the error (Type 'boolean' is not assignable to type 'boolean[]') occurs looks like this:
private switchTabs() {
this.setState({ setData: !this.state.setData});
}
CodePudding user response:
per @evolutionxbox comment:
private switchTabs() {
this.setState({ setData: this.state.setData.map( x=>!x});
}
using .map will apply a function against each element in an array. This is nice, tidy notation. This is inverting each boolean value in the array. I'm not exactly sure what will happen if your array contains a non-boolean element though.
CodePudding user response:
You're denying the array of booleans !this.state.setData
which evaluates to false. Thus throwing that error.
Instead you should create a copy of the array and modify the desired index
private switchTabs(tabIndex) {
const newData = [...this.state.setData]; //copying the array
newData[tabIndex] = !newData[tabIndex];
this.setState({ setData: newData});
}