Home > Blockchain >  Cannot set properties of undefined javascript
Cannot set properties of undefined javascript

Time:08-05

I'm having trouble fetching from an API from javascript, and I'm getting the error

"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'ytData')"

Here is the code:

const url = `https://www.googleapis.com/youtube/v3/channels?key=${youtubeKeys.key}&part=statistics&id=${youtubeKeys.id}`

class Homepage extends React.Component {
  constructor() {
    super()
    this.ytData = []
  }

  getData() {
    fetch(url).then(this.handleResponse)
  }

  handleResponse(response) {  
    response.json().then((json) => {
      console.log(this.ytData)
      this.ytData.push(json.items[0].statistics)
      console.log(this.ytData)
    })
  }

  componentDidMount() {
    console.log(this.ytData)

    this.getData()
  }

I am importing youtubeKeys, and there are more of the function, since this is a React website I am creating.

Thanks in advance!

CodePudding user response:

you could just make your api calls inside the componentDidMount method.

  class Homepage extends React.Component {
  constructor() {
    super();
    this.state = {
      ydata: []
    };
  }

  componentDidMount() {
    fetch(url)
      .then((response) => response.json())
      .then((json) =>
        this.setState({
          ydata: json
        })
      );
  }
 render(){
  return(
    // you can render your data here
   )
  }
}

your data is saved in the state, and can be accessed by this.state.ydata

  • Related