Ad

React - Set State And Get Value Simultaneously

- 1 answer

I am making a ToDo App with React. I have the following data:

getInitialState: function(){
    return {
        name:"Michael",
        tasks:[
            {task:"Go to the gym", completed:false, id:1 }, 
            {task:"Do yoga", completed:false, id:2 },
            {task:"Buy groceries", completed:true, id:3 },
            {task:"Get tire fixed", completed:true, id:4}
        ],
        numCompleted:null
    }
},

How can I get the value of numCompleted to be shown in the initial state? I cannot calculate it before it is instantiated.

Thanks for the help.

Ad

Answer

Since this is a "computed" property, that will change whenever state changes anyway, why not just do this in your component's render?

getInitialState: function(){
    return {
        name:"Michael",
        tasks:[
            {task:"Go to the gym", completed:false, id:1 },
            {task:"Do yoga", completed:false, id:2 },
            {task:"Buy groceries", completed:true, id:3 },
            {task:"Get tire fixed", completed:true, id:4}
        ]
    }
    render: function () {
      let numCompleted = this.state.tasks.reduce(function (completed, task) {
        return completed + task.completed ? 1 : 0;
      }, 0);

      // render tasks
    }
},
Ad
source: stackoverflow.com
Ad