0.1.3 • Published 7 years ago

react-prepare-wrapper v0.1.3

Weekly downloads
2
License
ISC
Repository
github
Last release
7 years ago

react-prepare-wrapper

a higher order component / wrapper for executing a task when a component mounts or receives props

Installation

npm install react-prepare-wrapper --save-dev

Usage

Here's a simple way to use this with the connect wrapper from react-redux to create a kind of 'smart container' that can auto-fetch missing state data:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import prepare from 'react-prepare-wrapper'

import {fetchThings} from 'actions/app'
import {selectThings} from 'selectors/app'
import {ThingsCard, LoadingSpinner} from 'components/app'

const mstp = state => ({
    things: selectThings(state)
})

const onProps = props => {
    const {things, dispatch} = props
    if(!things) {
        dispatch(fetchThings())
    }
}

@connect(mstp)
@prepare(onProps)
export default class ThingsContainer extends Component {

    render() {
        const {things} = this.props
        return (
            <div className="things">
                {things ?
                    <ThingsCard things={things} />
                    : <LoadingSpinner />
                }
            </div>
        );
    }
}

When a ThingsContainer is mounted with an empty global state, it dispatches an action to fetch things and meanwhile renders <LoadingSpinner/>. After things is successfully fetched and merged into the global state via a reducer, the component will be rerendered with <ThingsCard/>.

Dev Dependencies

License

ISC