Giter Club home page Giter Club logo

easy-redux's Introduction

easy-redux

Helpers to facilitate the work with redux

License

See the LICENSE file for license rights and limitations (MIT).

Основное предназначение - уход от размывания кода на actions, constants, types. Компонента становится независимой, инкапсулирует в себе все данные и методы которые нужны для работы.

Установка:

    npm i easy-redux -S

В данном случае структура компоненты внутри приложения принимет следующий вид:

    /components
        /MyComponent
            actions.js
            component.js
            index.js                        
//index.js
import {PropTypes} from 'react';
const {bool, string, array} = PropTypes;
export const dataShape = {
    isWaiting: bool,
    isFailed: bool,
    status: string.isRequired,
    likes: array.isRequired,
};
export const STORE_KEY = 'likes';
export MyComponent from './component';
//actions.js
import {createActions} from 'easy-redux';
import {STORE_KEY} from './index';
const ACTION_RESET = 'increment';
const ACTION_REMOTE_LIKES = 'remote_like';

const initialState = {
    isWaiting: false,
    isFailed: false,
    status: 'expired',
    likes: [],
};

export default const actions = createActions({
    initialState, 
    storeKey,
    actions: {
        [ACTION_REMOTE_LIKES]: {
            action: userId => ({promise: request => request('/api/likes').get({userId})}),
            handlers: {
                onWait: (state, action) => ({...state, isWaiting: true, isFailed: false}),
                onFail: (state, action) => ({...state, isWaiting: false, isFailed: true}),
                onSuccess: (state, action) => ({...state, isWaiting: false, likes: action.result, status:'updated'})
            }
        },
        [ACTION_RESET]: {
            action: () =>({}),
            handler: (state, action) => ({...state, ...Object.assign({}, initialState)})
        }
    }
});

export const loadLikes = actions[ACTION_REMOTE_LIKES];
export const reset = actions[ACTION_RESET];
  
  //component.js
import {Component, PropTypes} from 'react';
import {STORE_KEY, dataShape} from './index';
import {connect} from 'react-redux';

import {loadLikes, reset} from './actions';

@connect(state => ({
    [STORE_KEY]: state[STORE_KEY]
}), {loadLikes, reset})
export default class MyComponent extends Component {
    static propTypes = {
        [STORE_KEY]: PropTypes.shape(dataShape),
        //actions
        loadLikes: PropTypes.func.isRequired,
        reset: PropTypes.func.isRequired
    };

    onUpdateClick = (e) => {
        this.props.loadLikes();
    };

    onResetClick = (e) => {
        this.props.reset();
    };

    render () {
        const {[STORE_KEY]: {status, isWaiting}} = this.props;
        return (
            <div>
                <p>{status}</p>
                <button onClick={this.onUpdateClick} className={isWaiting ? 'waiting' : ''}>Update</button>
                <button onClick={this.onResetClick}>Reset</button>
            </div>
        );
    }
}

  

Соответственно при импорте компоненты в глобальном сторе появится поле likes (STORE_KEY), подключится reducer и actions

easy-redux's People

Contributors

welljs avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.