An initial state value becomes props value from an upper component.【React】

Tomoharu Tsutsumi
2 min readDec 23, 2019

When I was coding react, I had a problem. It was a little difficult and had a trap, so I summarise this event.

Issue I had

The code is below.

export default class HeaderTutorialWrapper extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
unDealtStepNum: 0,
};
} componentDidMount() {
axios
.get('/api/v1/total_steps/undealt_step')
.then(res => {
this.setState({ unDealtStepNum: 10});
})
.then(err => {
console.log(err);
});
}
 render(){
return (
<div>
<HeaderTutorial
unDealtStepNum={this.state.unDealtStepNum} => gives 10
/>
</div>
);
}
}

This is an upper component. Also, next is a lower component.

export default class HeaderTutorial extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
contentsNum: this.props.unDealtStepNum,
};
}
 render() {
return(
console.log(this.props.unDealtStepNum); => becomes 10
console.log(this.state.contentsNum); => doesn't become 10 Oops!!
)
 }

Temporary solution

I consulted with CTO, he gave an answer. It was getDerivedStateFromProps.

We can give an initial state to a lower component as props with this life cycle method. Good!

Another issue took place

I coded getDerivedStateFromProps. However, this.setstate doesn’t work!! React developers have already recognised this issue and solved it.

I managed to write a right code with this way.

The right code

I added this code into the lower component.

static getDerivedStateFromProps(props: Object, state: Object) {  const prevProps = state.prevProps || {};  const contentsNum =    prevProps.unDealtStepNum !== props.unDealtStepNum      ? props.unDealtStepNum      : state.contentsNum;  return {    prevProps: props,    contentsNum,  };}

React is difficult…

If you think this article good, please follow me!

I update articles once a week!

https://twitter.com/tomoharutsutsum

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet