John Griffiths
John Griffiths

Reputation: 585

setting initial state with componentwillreceiveprops?

I'm writing an image component and stuck on componentwillreceiveprops.

Here's the gist of the component...

class ImageField extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    image: '',
    imagePreviewUrl: '',
  };
}

componentWillReceiveProps(newProps){
  if (newProps.content === this.props.content) {
    return;
  }

  this.setState({
    image: this.props.content
  }, function() {
    console.log(this.state.image)
  })
}

I've got a react form which sends a block of json to the ImageField component that when componentWillReceiveProps fires should set this.state.image to that json block.

However it never sets it and when it hits console.log it returns undefined for this.state.image

Now if I do this.setState twice it writes json to the this.state.image but don't want to do that as it's probably the wrong way of doing it.

Stuck, what's the proper way of doing this?

Upvotes: 1

Views: 675

Answers (1)

Sajith Edirisinghe
Sajith Edirisinghe

Reputation: 1727

First you need to initialize the state in your constructor as shown below because when the component is created initially, the componentWillReceiveProps() is not invoked, rather the constructor will be invoked with the initial props.

constructor(props) {
  super(props);
  this.state = {
    image: props.content,
    imagePreviewUrl: '',
  };
}

Next modify componentWillReceiveProps() as below so that you invoke setState() using the newProps.

componentWillReceiveProps(newProps){
  if (newProps.content === this.props.content) {
    return;
  }

  this.setState({
    image: newProps.content
  }, function() {
    console.log(this.state.image)
  })
}

Upvotes: 1

Related Questions