0

In React assuming I have an integer variable called myProperty which is returned from getDafaultProps, if I console.log(myProperty) before and after I call this.setProps(myProperty+1) in a update function the console logs the same value for myProperty.The property updates after the function ends and next time I called my function myProperty is the new value but does anyone know why or rather explain to me why myProperty is not updated immediately when this.setProps is called?

thanks for taking your time to respond. relevant code below

getDefaultProps: function() {
    return { colorIndex: -1 };
},
update: function() {
    console.log("clicked and index is " + this.props.colorIndex); //returns -1
    this.setProps({colorIndex: this.props.colorIndex + 1});
    console.log("index is now " + this.props.colorIndex); /still returns -1
},
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
woodwick
  • 3
  • 1
  • if you have a variable with value changes, you should use `setState` and `this.state` object – Olivier Boissé Feb 07 '17 at 17:01
  • since I cant find the edit I did some thinking. Is it because it is an asynchronous function and just hasnt had time to update by the time I console log? Just a thought. – woodwick Feb 07 '17 at 17:02
  • 1
    Why are you using the deprecated `setProps` in the first place? I don't even think it's in current React. (Confirmed, removed in 0.14; https://github.com/facebook/react/pull/5570) In any case, I'd assume that like `setState` it doesn't happen right away. See also http://stackoverflow.com/a/25142742/438992. Over two years ago. – Dave Newton Feb 07 '17 at 17:02
  • I see thanks for the answers. Why was setProps deprecated and setState the way to go? – woodwick Feb 07 '17 at 17:04
  • @woodwick you should not modify the props of the component itself. Props are variables that are handled outside the component (from the parent component, or outside React, if it's the top level component) and passed **as props** to your component (top-down). They should be **immutable** in your component. – mrlew Feb 07 '17 at 17:34
  • @mrlew thanks for the clarification mate – woodwick Feb 07 '17 at 20:37
  • @woodwick you're welcome. Good luck in your project – mrlew Feb 07 '17 at 20:38

1 Answers1

1

Both setState and setProps do not immediately mutate - From Reacts documentation:

https://facebook.github.io/react/docs/react-component.html#setstate

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Your update method should call setState, and your render method will execute on basis of the updated state.

flexicious.com
  • 1,601
  • 1
  • 13
  • 21