Reputation: 5761
I have the following method inside a react component:
addWidget = (index) => {
let endX = this.state.widgets.reduce((endX, w) => endX.w + w.w, 0)
console.log(endX);
if (endX === 12) endX = 0
this.setState({
widgets: this.state.widgets.concat({
...this.state.availableWidgets[index],
i: uuid(),
x: endX,
y: Infinity,
})
})
}
the "addWidget" is in the render method as follow:
render() {
const { widgets } = this.state
return (
<div>
<Button type="secondary" onClick={() => this.addWidget(0)}>Add small</Button>
<Button type="secondary" onClick={() => this.addWidget(1)}>Add large</Button>
<Dashboard
widgets={widgets}
onLayoutChange={this.onLayoutChange}
renderWidget={this.renderWidget} />
</div>
)
and I have the state as follow:
...
state = {
widgets: [],
availableWidgets: [
{
type: 'compliance-stats',
config: {
},
w: 1,
h: 1,
},
{
type: 'compliance-stats',
config: {
},
w: 3,
h: 2,
}
]
}
...
to start width, "this.state.widgets" is an empty array which gets populated on click with the concat method. The first value of endX will be 0; however after that I get NaN
Upvotes: 2
Views: 101
Reputation: 31024
You are setting the initial value of the accumulator as 0
.
But you treat it like it is an object:
endX.w + w.w
it's like doing:
0.w + w.w
Which actually will do this:
undefined + w.w
This will produce NaN
.
Try to change it to this:
let endX = this.state.widgets.reduce((endX, w) => endX + w.w, 0)
Upvotes: 3
Reputation: 1126
Your start value is 0 but you reference endX.w
which is undefined so adding will produce NaN
.
Let the start value be {w:0}
Upvotes: 1