title: React: How do I move my ajax api call into a separate component?
body: <p>Here is a typical container component that is working perfectly well:</p>
  
  <pre><code>const API = 'https://randomuser.me/api/?results=5';
  class App extends Component {
  
      constructor(props) {
        super(props);
        this.state = { profiles: [] };
      }
  
      componentDidMount() {
        this.fetchProfiles();
      }
  
      fetchProfiles() {
        let url = API;
        fetch(url)
          .then( (res) =&gt; res.json() )
          .then( (data) =&gt; {
            let results = data.results;
            this.setState({
              profiles: results 
            });
          })
          .catch( (error) =&gt; console.log('Oops! . There Is A Problem', error) );
      }
  
      render() {
        // rendering child component here
      }
  }
  
  export default App;
  </code></pre>
  
  <p>What I am trying to do now is move the <code>fetchProfiles</code> function into a separate <em>api</em> component.</p>
  
  <p>So I make a <code>profiles.js</code> file in an <code>api</code> folder in my project:</p>
  
  <pre><code>const API = 'https://randomuser.me/api/?results=5';
  
  export function fetchProfiles() {
    let url = API;
    fetch(url)
    .then( (res) =&gt; res.json() );
  }
  </code></pre>
  
  <p>And now my main component imports it and uses it like so:</p>
  
  <pre><code>import { fetchProfiles } from '../api/profiles.js';
  
  
  const API = 'https://randomuser.me/api/?results=5';
  class App extends Component {
  
      constructor(props) {
        super(props);
        this.state = { profiles: [] };
      }
  
      componentDidMount() {
        fetchProfiles.then((data) =&gt; {
          let results = data.results;
            this.setState({
              profiles: results 
            });
        });
      }
  
    // render call etc
  </code></pre>
  
  <p>But when I run the call in <code>componentDidMount</code> like this, I get this error: <code>Uncaught TypeError: _profiles.fetchProfiles.then is not a function</code>. I am trying to chain with <code>then</code> because the fetch api returns <code>res.json()</code> as a promise.</p>
  
  <p>I tried wrapping <code>fetchProfiles</code> in a outer function, in a new promise too! But nothing works!! What am I doing wrong here? Please help with this refactoring.</p>