0

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?

2 Answers 2

2

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,
       });
   });
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.