Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux use HOC with connected component

I am in the middle of my first React Native project. I would like to create a HOC that deals purely with syncing data from an api. This would then wrap all my other components.

If I am correct my DataSync component would enhance all other components by doing the following in the export statement:

export default DataSync(SomeOtherComponent);

The concept I am struggling with is that SomeOtherComponent also depends on the React Redux Connect method for retrieving other redux state. My question is how can I use both together? Something like this?

export default DataSync(connect(mapStateToProps, mapDispatchToProps)(SomeOtherComponent));

I may have completely misunderstood the concept here so I would really appreciate some pointers

EDIT

To explain further:

My DataSync HOC would purely handle the syncing of data between the app and would be the top level component. It would need access to auth state and would set the data in Redux (in this case orders) for all other components.

Components nested within the DataSync HOC need access to the retrieved data, routes and they in turn create state (orders) that must be synced back to the server periodically.

like image 729
mtwallet Avatar asked Nov 29 '16 12:11

mtwallet


People also ask

Is React Redux Connect is hoc?

Whereas a component transforms props into UI, a higher-order component transforms a component into another component. HOCs are common in third-party React libraries, such as Redux's connect and Relay's createFragmentContainer .

Is connect function a hoc?

Yes, connect is also HOC and you can nest them arbitrary since a HOC returns a component.

How do I link a functional component to Redux?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.


1 Answers

Here is a simple example how it works

const AppWrapper = MainComponent =>
  class extends Component{
    componentWillmount(){
      this.props.fetchSomething()
    }
    componentDidUnmount(){
      this.props.push('/')
    }
    render(){
      return (
        <div>
          {this.props.fetchedUsers === 'undefined' ? 
            <div> Do something while users are not fetched </div> :
            <MainComponent {...this.props}/>}
        </div>
      )
    }
  }



const App = ({users}) => {
  // just example, you can do whatever you want
  return <div>{JSON.stringify(users)}</div>
};

// mapStateToProps will be in HOC -> Wrapper
// mapDispatchToProps will be in HOC -> Wrapper

/* you may use DataSync as you want*/
export default connect(mapStateToProps, mapDispatchToProps)(AppWrapper(App))

Useful HOC link

like image 157
The Reason Avatar answered Oct 03 '22 12:10

The Reason