Tieu Duong Tu
Tieu Duong Tu

Reputation: 84

Variable inside componentDidMount are undefined using Reactjs

I have the following block of code:

const UserNotification = ({ user }) => {
  const url = `https://api.thingspeak.com/channels/${user.channel}/feeds.json?&dynamic=true`;
  console.log(url); //https://api.thingspeak.com/channels/594944/feeds.json?&dynamic=true OK
  return <UserNoti url = { url } />
}

class UserNoti extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
      isLoaded: false,
    };
  }

  componentDidMount() {
   fetch(url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,
        });
      });
  }
 render() {...}}

However, I get a 'url' is not defined no-undef for the following line: fetch(url) in componentDidMount(). How can I call url variable inside componentDidMount method?

Upvotes: 0

Views: 559

Answers (2)

Matei Radu
Matei Radu

Reputation: 2078

In UserNotification you pass url as a component prop. With ES6 class components, props are accessed using this.props.propName. So, in your case, you should do:

componentDidMount() {
  fetch(this.props.url)
    .then(res => res.json())
    .then(json => {
      this.setState({
        isLoaded: true,
        items: json,
      });
    });
}

More info from the official React documentation on Components and Props.

Upvotes: 2

UjinT34
UjinT34

Reputation: 4987

Use this.props.url to access url propery you pass to UserNoti class.

componentDidMount() {
   fetch(this.props.url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json,
       });
   });
}

Upvotes: 2

Related Questions