Reputation: 177
I'm having trouble using setState on an empty array. I have an empty array in my state, and I'm trying to populate it from another function using setState.
dataProcessing.js
:
const calculate = () => {
let series = [{
name: "Sports",
data: [
{
name: "Baseball",
y: 13
},
{
name: "Football",
y: 20
}
}]
return series;
}
export default calculate;
Main.js
:
import calculate from './dataProcessing';
export default class Main extends PureComponent {
constructor() {
super();
this.state = {
series: []
};
}
calc = () => {
this.setState = ({
series: [... calculate()]
})
}
}
After the calc()
function gets executed, this.state.series
is still an empty array. What am I doing wrong? Thanks in advance!
Upvotes: 0
Views: 60
Reputation: 2319
dataProcessing.js:
const calculate = () => {
let series = [{
name: "Sports",
data: [
{
name: "Baseball",
y: 13
},
{
name: "Football",
y: 20
}
]
}]
return series;
}
export default calculate;
Main.js:
import calculate from './dataProcessing';
export default class Main extends PureComponent {
constructor() {
super();
this.state = {
series: []
};
}
calc = () => {
this.setState = ({
series: [...calculate()]
}, () => {
console.log("series", this.state.series)
})
}
}
Upvotes: 0
Reputation: 15268
You want a method bound to this
, and to call this.setState, not to set this.setState =
calc() {
this.setState({
series: [... calculate()]
})
}
Upvotes: 1
Reputation: 5434
this.setState
is async. Once you call setState your component will re-render
You can use the callback of setState to get the new updated state.
this.setState = ({
series: [...calculate()];
}, (newState) => {
console.log(newState);
});
Upvotes: 0