0

I am trying to pass -from parent to child component- some data as props and I would like to set this prop to initial state.

class EditContact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name,
      phone_number: this.props.phone_number,
      address: this.props.address
    };
    this.handleInputChange = this.handleInputChange.bind(this);
  }
  ...
}

I am not getting any errors, but if I console.log this.state.name I get nothing. or when I check it in chrome-s react add-on I can see the props values, but state remains "".

I have also tried to sort it with getDerivedStateFromProps in componentDidMount, I can set it with that but then it doesn`t let me change the state later on...Why?! What can be wrong?

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
Gabi C
  • 461
  • 3
  • 10
  • 21
  • 2
    How are you using this `EditContact` component in your app? It might be that you are loading the data in the parent component asynchronously, so when `EditContact` is created the props are not set yet. – Tholle Nov 07 '18 at 00:29
  • please provide the code where you're trying to `console.log` – You Nguyen Nov 07 '18 at 00:36

2 Answers2

0

Make sure the value of props is the expected when you assign them to the state.

super(props);
debugger; // This will act as a break point in chrome

Most likely the issue is that the value of props is empty by the time they are assigned to the state.

  • Yes, that is the issue,but I cannot seem to figure it out how to solve it. I am making a phonebook app. Filtering, sorting, adding, deleting, editing. Everything is done apart from editing. In order to be able to complete the project I should set the initial state to this.props but when it renders it is still empty and I am not sure how to work around it. – Gabi C Nov 07 '18 at 11:18
  • Well you could use componentDidUpdate and do setState there but you have to be carefull and wrap it in a condition or it will cause an infinite loop. Can't you create the component when the props have value? I say this cause since you have to do setState to change the value of props you should be able to control that, I think. – Rodrigo Martín de Lamo Nov 07 '18 at 11:57
0

Use

props.name

instead of

this.props.name
Andrew P.
  • 160
  • 1
  • 8