Reputation: 17
I want to start a loop and add a certain number of elements to the array. "newTester + =" does not add values to the array. How to solve the problem?
state = {
tester: []
}
handleChange(value) {
this.setState({tableAmountColumns: value});
let i;
let newTester;
for ( i = 0; i < value; i++) {
newTester +=
{
key: 1,
qwe: "<h1>Hello world!</h1>"
};
this.setState({ tester: [...this.state.tester, newTester ] })
}
}
Upvotes: 1
Views: 715
Reputation: 1842
newTester
needs to be initialized as an empty array, otherwise its value is undefined
. You can't +=
anything to undefined
(or to an array, for that matter). You need to push()
elements into it:
handleChange(value) {
this.setState({tableAmountColumns: value});
let newTester = []; // <-- Important!
for (let i = 0; i < value; i++) {
newTester.push({ key: 1, qwe: "<h1>Hello world!</h1>" });
}
this.setState({ tester: [...this.state.tester, ...newTester] })
}
Upvotes: 1
Reputation: 397
Set an empty array as a default value for newTester
variable and then push objects. Also, you can take setState
call for setting tester
state outside of the for loop and merge two setState
calls for setting tester
and tableAmountColumns
values in order to avoid multiple rerenders.
EDIT: Also, spread newTester
array while setting tester
state.
state = {
tester: []
}
handleChange(value) {
this.setState({});
let i;
let newTester = [];
for ( i = 0; i < value; i++) {
newTester.push(
{
key: 1,
qwe: "<h1>Hello world!</h1>"
});
}
this.setState({
tableAmountColumns: value,
tester: [...this.state.tester, ...newTester ]
})
}
Upvotes: 1