redux-call

React utils for calling components methods via redux store

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
redux-call
0.0.76 years ago6 years agoMinified + gzip package size for redux-call in KB

Readme

About

redux-call is simple util to add ability to execute React component methods via Redux. It can be useful when you need to be able to conrol component from any part of your app

Installation

``` npm i --save redux-call ```

How to use

STEP ONE: you need to add redux-call reducer to your app: ```javascript import {combineReducers} from "redux"; import {callReducer} from "redux-call"; export default combineReducers({
commands: callReducer
}); ``` STEP TWO: you need to provide this "commands" store field to your component and run enableCalls method in constructor: ```javascript import React, {Component} from "react"; import {connect} from "react-redux"; import {enableCalls} from "redux-call"; export const COMPONENTID = "MyAwesomeComponentId"; export class MyAwesomeComponent extends Component {
constructor(props) {
super(props);
enableCalls(this, COMPONENT_ID, "commands");
}
playMedia() {
this.videoElement.play();
}
seekMedia(newTime) {
this.videoElement.currentTime = newTime;
}
getCurrentMediaTime() {
return this.videoElement.currentTime;
}
...
} const mapStateToProps = (state) => {
return {
commands: state.commands
}
}; export default connect(mapStateToProps)(MyAwesomeComponent); ``` STEP THREE: Now you can call MyAwesomeComponent methods by dispatching redux actions: ```javascript import {dispatch} from "store"; import {call} from "redux-call"; import {COMPONENT
ID} from "MyAwesomeComponent.js"; let playMediaAction = call(COMPONENTID, {method: "playMedia"}); let seekMediaAction = call(COMPONENTID, {method: "seekMedia", args: 10}); let getCurrentTimeAction = call(COMPONENTID, {method: "getCurrentMediaTime", callback: (currentTime) => {
console.log(`Current playback time is: ${currentTime}`);
}}); dispatch(playMediaAction); dispatch(seekMediaAction); dispatch(getCurrentTimeAction); ```

Options

enableCalls(componentInstance, componentId, commandsAccessor) | Param | Type | Description | | --- | --- | --- | | componentInstance | object | React component instance (just pass this in constructor) | | componentId | string/number/Symbol | Unique Id of component that will be used for calling | | commandsAccessor | string | name of component property that contains commands state (result of callReducer) | call(componentId, {method, args, callback}) | Param | Type | Description | | --- | --- | --- | | componentId | string/number/Symbol | Unique Id of component that must be called | | method | string | component method name that must be called | | args | array | array of arguments that must be passed to method | | callback | function | callback that will be executed with result of method |