Home > Software engineering >  fetch() retrieved data in JS (React) throws error with no apparent reason
fetch() retrieved data in JS (React) throws error with no apparent reason

Time:03-30

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:

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...

CodePudding user response:

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.

  • Related