Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data and then render it to dom React

Hi I am fetching data from an api and I would like to take the data and render it to the dom but I am the error "Uncaught TypeError: Cannot read property 'map' of undefined at Topicselect.render"

Here is essentially what I am doing, although I have abstracted away anything that is not directly relevant to the question, such as actual topic names, imports, etc :

class Topics extends Component{
   constructor(props){
     super(props);
     this.state = {
       topics: []
     }
   }
    componentWillMount(){
        fetch('/api').then((res)=>r.json().then((data)=>{
               // push topics into this.state.topics somehow
        }) 
       console.log(this.state.topics) //returns ['topic1','topic2','topic3'];
    } 
   render(){
     const list = this.state.topics.map((topic)=>{
         return(<li>{topic}</li>);
     })
    return(
      <ul>
        {list}
      </ul>
     )
    }
}

Can anyone tell me how to fix this? I saw an answer on here that said to use componentDidMount instead of componentWillMount but that isn't working for me

like image 327
moesh Avatar asked Dec 07 '25 13:12

moesh


1 Answers

You are missing a closing bracket ) after the fetch and it's indeed recommended to use componentDidMount() instead of componentWillMount() for fetching data from an API.

Also don't forget to use this.setState({ topics: data.howeverYourDataIsStructured }); after you receive the data from the API to ensure a rerender of the component.

class Topics extends Component{
  constructor(props){
    super(props);
    this.state = {
      topics: []
    }
  }

  componentDidMount() {
    fetch('/api').then((res)=>r.json().then((data)=>{
      this.setState({ topics: data.topics });
    }));
    console.log(this.state.topics) //returns [];
  }

  render() {
    console.log(this.state.topics) //returns [] the first render, returns ['topic1','topic2','topic3'] on the second render;
    return(
      <ul>
        {this.state.topics.map(topic => (
          <li>{topic}</li>
        ))}
      </ul>
    )
  }
}
like image 194
Tom Van Rompaey Avatar answered Dec 09 '25 02:12

Tom Van Rompaey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!