Can't re-render components using react-starter-kit

69 Views Asked by At

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>
    );
  }
}

1

There are 1 best solutions below

0
Daisuke SHIBATO On

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