React + NodeJs Fetch issue

Tags: , ,



I am trying to fetch the following results of my api (which is working well) http://localhost:5000/api/continents

{"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devias"},{"continentId":1,"CName":"Lorencia"}]}

into a react component (a simple array to begin with).

Endpoint code extracted from server.js:

app.get('/api/continents', (req, res) => {
    connection.query(SELECT_ALL_CONTINENTS_QUERY, (err, results) => {
        if(err){
            return res.send(err)
        }
        else{
            return res.json({
                data: results
            })
        }
    });
});

Here is my continents.js code:

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

class Continents extends Component {
    constructor() {
        super();
        this.state = {
            continents: []
        }
    }

    ComponentDidMount() {
        fetch('http://localhost:5000/api/continents')
            .then(res => res.json())
            .then(continents => this.setState({continents}, () => console.log('Continents fetched..', continents)));
    }

  render() {
    return (
      <div>
        <h2>Continents</h2>
      </div>
    );
  }
}

export default Continents;

And here is the App.js code:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Continents from './components/continents/continents';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Developed with NodeJS + React</h1>
        </header>
        <Continents />
      </div>
    );
  }
}

export default App;

Issue:

continents array is empty. No data fetched. However, there are no errors. I would very much appreciate if someone could guide me in the right direction to solve this. Thank you very much.

Answer

ComponentDidMount is a function so it shouldn’t be capitalized it should be: componentDidMount.

And you’re passing the incorrect value to the setState method, you should pass {continents: continents.data} instead of the continents object itself.

The corrected code:

componentDidMount() {
    fetch('http://localhost:5000/api/continents')
        .then(res => res.json())
        .then(continents => this.setState({continents: continents.data}));
}


Source: stackoverflow