0

I am trying to build a basic website that fetches a user list online and displays their names. Instead of using fetch.then, I put the fetch function within an async function and update the state within that very same function. The function is placed in componentDidMount. However, I received the error cannot read properties of undefined (reading 'setState'). I have tried changing to fetch.then() and it works. Could you tell me the reason behind this? Thank you very much

import React, {Component} from 'react'

class App extends Component{
  constructor (){
    super()
    this.state = {
      monsterList: []
    }}


    componentDidMount(){
      async function fetchingData(){
        let data = await fetch('https://jsonplaceholder.typicode.com/users')
        data = await data.json()
        this.setState(()=>{
          return {monsterList: data}
        })
      }
      fetchingData()
    }
  render() {
    return (
      <div className='App'>
          {this.state.monsterList.map(monster => {
            return (
              <div key={monster.id}>
                  <h1>{monster.name}</h1>
              </div>
            )
          })}
      </div>
      
    )
      }
}




export default App;
  • 2
    It's an issue with `this` binding, you can fix it by redefining `fetchingData` using an arrow function. But also this problem is avoided entirely if you switch to funcitonal components with hooks (which you should do if possible) – Henry Woody Jul 13 '23 at 09:21
  • componentDidMount() { const self = this; async function fetchingData() { let data = await fetch("https://jsonplaceholder.typicode.com/users"); data = await data.json(); //console.log(data); //this.setState({monsterList: data}) self.setState({ monsterList: data }); } fetchingData(); } replace it with your code. "Learn About this inside regular function and binding" – JASBIR SINGH Jul 13 '23 at 09:25
  • @HenryWoody Thank you very much. I fixed the problem by defining the function in the constructor instead of in the componentDidMount. – Trung Lương Jul 13 '23 at 09:26
  • you can not make api call inside a constructor function it is bad practice. – JASBIR SINGH Jul 13 '23 at 09:30
  • @JASBIRSINGH It worked! Thank you very much. Where do you suggest I could learn more about this? I am a beginner – Trung Lương Jul 13 '23 at 09:31
  • @JASBIRSINGH I will remember that. Thank you very much – Trung Lương Jul 13 '23 at 09:33

0 Answers0