Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fetch() retrieved data in JS (React) throws error with no apparent reason

I think is related to babel or javascript-language package in the text editor (Atom), because I am actually coding along a tutorial and I am just starting and I already get error after running "npm start or yarn start". I have exactly the same code as in the tutorial but in my case it prompts the following errors:

enter image description here

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import './App.css'
import React, {Component} from 'react'

class App extends Component {
  constructor(){
    super()
    this.state= {
      monsters: []
    };
  }
  componentDidMount(){
    fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(data =>
      this.setState(
        ()=>{
          monsters: data
        }
      )
    );
  }
  render(){
    return <div className='App'>
    <h1>{this.state.monsters}</h1>
    <ul>{this.state.monsters.map((monster)=>{
      return <li>{monster.name}</li>;
    })}</ul></div>;
  }
}

export default App;

I hope someone can give me a hint on what should I do or try, in order to fix this…

>Solution :

The curly braces here make this a function, and it’s expecting a return value. Your intention is to return an object. To do that, add parentheses.

// From this:
()=>{
  monsters: data
}

// To this:
()=> ({
  monsters: data
})

That should do the trick.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading