title: How can I turn a function used in many components into its own component which I can reuse across the app?
body: <p>I have a fetch request used on multiple pages, and would like to turn it into a component to simply call in whenever it's needed. This is proving to be harder than I thought, and it's bring up a number of issues. </p>
  
  <p>I have tried using the wrappedComponent function but not sure if that's the solution as it's still not working. It's now saying that the fetchPosts class constructor cannot be invoked without new. </p>
  
  <pre><code>        const that = this; 
          fetch ('/testrouter')
          .then (response =&gt; {
              return response.json(); 
          }).then(jsonData =&gt; {
              that.setState({posts:jsonData})
          }).catch(err =&gt; {
              console.log('Error fetch posts data '+err)
          });
      }
  </code></pre>
  
  <p>This is what I want to turn into a component, so that I can just call it by it's name from another one inside componentDidMount. I have tried doing this: </p>
  
  <pre><code>function fetchPosts(WrappedComponent) {
      class FetchPosts extends Component {
       constructor(props) {
           super(props)
           this.state = {
               posts: []
           }
       }
  
       fetchAllPosts() {
           const that = this; 
          fetch ('/testrouter')
          .then (response =&gt; {
              return response.json(); 
          }).then(jsonData =&gt; {
              that.setState({posts:jsonData})
          }).catch(err =&gt; {
              console.log('Error fetch posts data '+err)
          });
      }
      render() {
          return (&lt;WrappedComponent 
          fetchAllPosts = {this.fetchAllPosts})
          /&gt;);
      }
  
  }
      return FetchPosts;
  
  }
  
  
  export default fetchPosts
  </code></pre>
  
  <p>Then importing it and calling it with fetchPosts but it's not working. </p>
  
  <p>I was hoping I would be able to create a component, add the code then import the component, but this is not working.</p>