Search code examples
javascriptreactjsassign

Don't understand how JavaScript assign operator interacts with a function


My problem is that I don't understand how assign operator is interpreted and interacts with a function. Let me explain

I was changing the state of my component, and I was doing something wrong that I couldn't see until I realize it, of course.

My component:

class UpdateLifeCycle extends Component {
  state = { src: urls[this.props.election] };

  componentWillReceiveProps(nextProps) {    
    this.setState = { src: urls[nextProps.election] };    
  }

  render() {
    return (
      <div>
        <p>Selected {this.props.election}</p>        
        <img //
          alt={this.props.election}
          src={this.state.src}
          witdh="250"
        />
        <p>{urls[this.props.election]}</p>
        <p>{this.state.src}</p>
      </div>
    );
  }
}

What I was doing, and is wrong is this piece

this.setState = { src: urls[nextProps.election] };    

and what I should be doing is passing it as a parameter instead of assigning it.

this.setState({ src: urls[nextProps.election] });    

Why does the JS interpreter allow you to assign and object to a function, and where is that object being assigned?


Solution

  • TL;DR

    setState is a variable which currently holds a function. There is nothing stopping you from changing its value and add an object there, because it is a variable. JavaScript was influenced by other functional programming languages and it is okay to assign a function to a variable.

    Explanation

    state is a special object in a React component, which you would access as this.state. setState is a special function in a React component, which allows you to modify the state. Actions are dispatched when the state is updated, however you should not directly modify the state of a React component, and should always use setState.

    setState is another variable in a JavaScript class (Your React Component is a class-based component), which by default holds the function to modify the state variable. You can override a variable in JavaScript and when you assign an object (the new state you wanted) to setState, you are changing the value of setState which can no longer now update the state variable.

    You would find React's docs helpful.