Search code examples
reactjsreduxflux

How to decouple a Component from it's own data fetching needs


When a component requires a certain set of data to be fetched before rendering, I usually do something along those lines:

class Comp extends Component {
  componentWillMount() {
    this.props.requestData() // triggeres in action in the wrapper
  }
  render() {
    const { data } = this.props.
    return (
       <div>
         {/* do something with data */}
       </div>
    )
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Comp)

Now I have two React SPA's in which I want to use this component. In one App the needed data needs to be fetched before the component is mounted, in another the data already exists. So I was wondering, if there is any best practice regarding the issue of fetching data that is a prerequisite for a component. Is there a way for the wrapper to listen to Comp's lifecycle? Should I just rename requestData to onComponentWillMount and listen to that for action triggering?

Ideally the component should have no concern about if or when to fetch.


Solution

  • You can create a HoC (Higher order Component) to wrap your vanilla Comp component and fetches the data on onComponentWillMount (and on onComponentWillReceiveProps). As you are using redux I imagine that your requestData() callback is creating a redux action that dispatches the data to the global store. Alternatively, if the data is local to this component you could keep it in the state of the HoC.