React props show up as undefined at first

Viewed 1163

I have a react component that makes an api call based on the data recieved by its props.

constructor(props) {
    super(props);
    this.state = { 
        followsUser: null
    }
componentDidMount() {
    console.log(this.props)
    axios.get(`http://127.0.0.1:8000/users/check/${this.props.id}`)
    .then(res => this.setState({ followsUser: res.data.follows }))
    .catch(err => console.log(err))
}

I call the component in another component like:

<FollowButton key={this.state.user.id} id={this.state.user.id} />

But in the browser console I get the following error:

GET http://127.0.0.1:8000/users/check/undefined 404 (Not Found)

This is what I see in the browser console: console

1 Answers

State-setting is an asynchronous operation, so whenever you're intending to act upon data that is somehow derived from state, it's wise to manually safeguard against undefined values that might be present before getting updated state.

constructor(props) {
  super(props);
  this.state = { 
    followsUser: null
  }
}

componentDidMount() {
  // one could write
  //
  // if (this.props.id)
  //
  // but if there's a possibility the id could be 0 (which is falsy),
  // it's safer to explicitly check for undefined.

  if (typeof this.props.id !== 'undefined') {
    axios.get(`http://127.0.0.1:8000/users/check/${this.props.id}`)
      .then(res => this.setState({ followsUser: res.data.follows }))
      .catch(err => console.log(err))
  }
}
Related