user2916134
user2916134

Reputation:

React - Set State and get value simultaneously

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.

Upvotes: 1

Views: 97

Answers (3)

Nick Tomlin
Nick Tomlin

Reputation: 29271

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

Upvotes: 0

Mike D
Mike D

Reputation: 251

Can you not just calculate that in the following manner:

getInitialState: function(){

   var _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}];

  var completedCount = 0;

  for( var i = 0; i < tasks.length; i++ ) {
     if ( task[i].completed ) {
        completedCount++;
     }
  }

   return {
       name:"Michael",
       tasks:_tasks,
       numCompleted: completedCount
   }

},

Upvotes: 0

Jeroen Noten
Jeroen Noten

Reputation: 3634

How about:

getInitialState: function(){
    var 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}
    ];
    return {
        name:"Michael",
        tasks:tasks,
        numCompleted:tasks.filter(function(task) {
            return task.completed;
        }).length
    }
},

You can just calculate it if you want...

Upvotes: 1

Related Questions