redux-provide
v0.1.2
Published
Redux Data Provider for ReactJS components
Downloads
1
Readme
redux-provide
Easily create Higher Order Components that allow you to connect any component to whatever part of the Redux State.
Wait, what?
When using Redux, you usually connect
a Smart Component to some part of your state in order to be able to either read some values from it or dispatch some actions. When your application grows bigger, you'll find that:
- Many components will probably use the same selectors or connect to the same parts of your Redux State;
- You'll have to
import
a lot of Action Creators, usually the same ones, all over the place because you'll need todispatch
them on more than a single smart component;
If you, like me, like to organize your application in modules (see my own application seed) you'll also find that
- Modules will end up depending on each other, thus defeating the concept of isolation and modularity
This library aims to mitigate these problems by allowing you to create ad-hoc HoCs to connect any component on the fly to whatever part of the Redux State, and provide it with bound action creators as well.
How?
First, install it using npm install redux-provide
Then, simply create a DataProvider file somewhere in your application structure where you define the selectors and the action creators you want to provide, and export it by wrapping it in a provide
function call (which is what this library exports):
DataProvider.js
import { createSelector, createStructuredSelector } from 'reselect'
import provide from 'redux-provide'
import { fetchPosts } from './ActionCreators'
const postsSelector = state => state.posts.items
const select = createStructuredSelector({
posts: postsSelector
})
export default provide(select, { fetchPosts })
You can now easily connect any component by simply wrapping it in the HoC exported by DataProvider.js
, like this:
MyComponent.js
import React from 'react'
import WithPosts from './DataProvider'
class MyComponent extends React.Component {
componentDidMount() {
// This action creator is bound, so it's already wrapped in a dispatch call
this.props.fetchPosts()
}
render() {
return (
<ul>
{this.props.posts.map( (post, index) => (
<li key={index}>{post.title}</li>
) )}
</ul>
)
}
}
export default WithPosts(MyComponent)
Do I really need this?
Well, it's up to you. It provides a layer of abstraction that is almost purely semantic, and it might not play well with your application so your mileage may vary. Also, the whole thing is 8 lines of code, so you probably should just copypaste it into your project. Here it is, for your convenience:
Provide.js
import React from 'react'
import { connect } from 'react-redux'
function provide(select, ActionCreators) {
return (WrappedComponent) => connect(select, ActionCreators)(WrappedComponent)
}
export default provide
License
MIT