Long Phan Long Phan - 1 month ago 6
React JSX Question

Why is my props undefined when i passed a defined state through?

I am trying to pass data to a child component and I keep getting an undefined prop. I think it may have an issue with when Im setting the state in the parent component. Should i not be using componentWillMount?

export default class AllItems extends Component {
constructor () {
super()
this.state=({ user: cookie.load('user')})
this.httpHandler = axios.create({
baseURL: 'http://localhost:3000/',
headers: {
'Authorization': this.state.user.token
}
})
}

componentWillMount() {
this.httpHandler('/products/')
.then(function (response) {
this.setState({ winks: response.data.data})
console.log(this.state.winks)
}.bind(this))
}
render() {
return (

<Winks products={this.state.winks} />

)
}
}

Answer

The problem is that your promise may not return before componentWillMount finishes and render is called. So products won't exist yet. You could do something like this:

render() {
  if (this.state.winks) {
    return (<Winks products={this.state.winks} />)
  } else {
    return (<div>No Winks yet</div>);
  }
}
Comments