State Updates May Be Asynchronous , what is exactly this.props?

by Santosh Kumar   Last Updated October 09, 2019 15:26 PM

state = { 
    {id:"cbhc", name:"surya",age:26,sex:"male"},
    {id:"rgt", name:"sachin",age:36,sex:"male"},
    {id:"cbcchc", name:"rahul",age:46,sex:"male"}

the above was the state of data in my application.

// Wrong
  counter: this.state.counter + this.props.increment,

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument :

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment

what was exactly here : props.increment ????

my piece of code :

const inc=this.state.increment;

this.setState((state, props) => ({
  counter: state.counter + inc

I want to know was props.increment is the "inc" variable i'm using .

Answers 1

As the React documentation states:

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.

I suggest to read further the official docs, especially Rendering a Component part.

Additionally setState() one here explains further:

this.setState((state, props) => {
  return {counter: state.counter + props.step};

Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.

I hope this helps!

October 09, 2019 15:13 PM

Related Questions

Async requests with data from store

Updated June 21, 2015 23:11 PM

Communication between Stores in Reactjs

Updated April 22, 2015 00:11 AM

Getting undefined for

Updated July 13, 2015 13:11 PM

Changing multiple states in an Object

Updated August 20, 2018 22:26 PM