-2

I am learning Redux with React. I am using dispatch like below

this.props.dispatch(uploadImage(formData, config, element_id));

My mapStateToProps is like below

const mapStateToProps = state => ({
    uploadImage: state.addressReducer.uploadImage
});

export default connect(mapStateToProps)(ModalElement);

I would like to get output like below

componentWillReceiveProps(nextProps) {
    if (nextProps.uploadImage) {
        this.setState({ photostatus: 'image' });
        console.log(this.state.photostatus)  // getting wrong output, not `image`
    }
}

Here is my Repo https://github.com/afoysal/mern/blob/master/client/src/components/ModalElement.js

abu abu
  • 6,599
  • 19
  • 74
  • 131

2 Answers2

1
 if (nextProps.uploadImage) {
    this.setState({ photostatus: 'image' 
  },()=>console.log(this.state.photostatus))
 }

check by changing this way

Kishan Jaiswal
  • 644
  • 3
  • 14
  • Thanks @Kishan Jaiswal for your solution. I know your solution. But my component needs `photostatus: 'image'` when I am calling it. setState Callback is not working here. – abu abu Jun 03 '19 at 05:08
  • 1
    https://stackoverflow.com/questions/39171184/not-able-to-set-state-in-componentwillreceiveprops-in-react please read this and also about the llifecycle on componentWillReceiveProps – Kishan Jaiswal Jun 03 '19 at 05:15
  • 1
    componentWillReceiveProps rendering is different from all other lifecycles – Kishan Jaiswal Jun 03 '19 at 05:15
  • Thanks @Kishan Jaiswal for your solution. What should I do here ? What is your opinion in this situation ? Should I use `componentDidUpdate` instead of `componentWillReceiveProps` ? Thanks. – abu abu Jun 03 '19 at 06:05
  • My issue is in `this.setState()`. How can I set the state of `photostatus` ? Thanks. – abu abu Jun 03 '19 at 06:10
1
componentWillReceiveProps(nextProps) {
    if (nextProps.uploadImage) {
        this.setState({ photostatus: 'image' }, () =>{
          console.log(this.state.photostatus)  // this.setState is asynchronous so you won't find the changes immediately
        }
        );
    }
}
Anita
  • 476
  • 3
  • 10
  • 24
  • Thanks @Anita for your solution. I know your solution. But my component needs `photostatus: 'image'` when I am calling it. setState Callback is not working here. – abu abu Jun 03 '19 at 05:07