0

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!

2
  • Where are you checking this.state.series? Commented Jun 6, 2020 at 4:20
  • I was calling it in the render() Commented Jun 6, 2020 at 4:28

3 Answers 3

1

You want a method bound to this, and to call this.setState, not to set this.setState =

  calc() {
    this.setState({
      series: [... calculate()]
    })
   }  
Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

Comments

0

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)
        })
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.