user1893649
user1893649

Reputation: 177

Having trouble using setState on an empty array

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

Answers (3)

Narendra Chouhan
Narendra Chouhan

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

user120242
user120242

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

hendrixchord
hendrixchord

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

Related Questions