user8767190
user8767190

Reputation: 25

React App: How to display data from API using fetch

I am trying to display school data from an external API using React. I'm just trying to display a school name to start. The school name appears in the console, but it doesn't show up in the browser. The API call is correct, as it works in Postman. Here is my code:

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

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      schoolName: '',
      // schoolData: {}
    }
  }

  fetchSchool(event) {
    event.preventDefault();

    const apiKey = 'XdOHSc8fKhMKidPu2HWqCZmMy9OxtCJamGC580Bi';
    const fields = `_fields=school.name,2015.aid.median_debt.completers.overall,2015.cost.tuition.in_state&school.name=${this.state.schoolName}`;
    const requestUrl = `https://api.data.gov/ed/collegescorecard/v1/schools?&api_key=${apiKey}&${fields}`;

    const school = fetch(requestUrl).then((res) => res.json()).then((data) => console.log(data.results[0]['school.name']));

    this.setState({
      schoolName: school
      // schoolData: school
    })
    console.log(this.state.schoolName);
  }

  setSchool(event) {
    event.preventDefault();
    this.setState({
      schoolName: event.target.value
    });
  }

  render() {
    // const schoolname = this.state.schoolName[0];
    // const {schooName} = this.state;
    return (
      <div>
        <form action="/school" method="GET" id="myform">
          <input type="text" className="form-control" id="enter_text" onChange={this.setSchool.bind(this)} />
            <button onClick={this.fetchSchool.bind(this)} type="submit" className="btn btn-primary" id="text-enter-button button submit">Submit</button>
        </form>
        <div>
        <p>School: {this.state.school} </p>
        </div>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 4706

Answers (2)

JJJ
JJJ

Reputation: 3352

fetch is asynchronous. Therefore, setState is being called before the data has been fetched.

To fix this, call this.setState from inside of your then function

const school = fetch(requestUrl)
  .then((res) => res.json())
  .then((data) => {
    console.log(data.results[0]['school.name'])
    this.setState({
      schoolName: data.results[0]['school.name'],
      schoolData: data.results
    })
  });

Upvotes: 1

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

In your render method change this line because schoolName is your state variable and not school.

<p>School: {this.state.school} </p>

to

<p>School: {this.state.schoolName} </p>

Upvotes: 0

Related Questions