1

Working with kriasoft/react-starter-kit to create a web application. It fetches objects from my api server, and shows them on a page. The app should show a loading icon while fetching the data.

My code doesn't re-render a component after fetching objects. It continues to show 'Loading...', even though I want to see 'Data loaded!'.

import React from 'react';
import fetch from 'isomorphic-fetch'

class Search extends React.Component {
  constructor(...args) {
    super(...args);

    this.getObjectsFromApiAsync = this.getObjectsFromApiAsync.bind(this);

    this.state = {
      isLoading: true,
    };
  }
  
  async getObjectsFromApiAsync() {
    try {
      const response = await fetch('http://localhost:3030/api');
      const content = await response.json();
      // console.log(content)
      this.setState({isLoading: false});
    } catch(e) {
      console.error(e);
    }
  }

  componentWillMount() {
    this.getObjectsFromApiAsync();
  };
  
  render() {
    if (this.state.isLoading) {
      return (
        <p>Loading...</p>
      );
    }
    
    return (
      <p>Data loaded!!</p>
    );
  }
}
Daisuke SHIBATO
  • 983
  • 2
  • 11
  • 23
  • I also want an example using [kriasoft/react-starter-kit](https://github.com/kriasoft/react-starter-kit) that re-renders a view when a state changes. – Daisuke SHIBATO Jan 12 '18 at 11:21
  • Cannot see anything bad with this code. Check if your console has errors – langpavel Jan 14 '18 at 05:11
  • Cannot find errors in my console. React components are in both _routes_ and _components_ directories. The Search class is under the _routes_ directory. Does re-render only work in files under the _components_ directory? – Daisuke SHIBATO Jan 14 '18 at 07:20

1 Answers1

1

Solved the problem by adding res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); to my api server. The problem was not in the React.

Here is the solution resource: https://stackoverflow.com/a/18311469/6209648

Daisuke SHIBATO
  • 983
  • 2
  • 11
  • 23