redux-call
v0.0.7
Published
React utils for calling components methods via redux store
Downloads
65
Maintainers
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:
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:
import React, {Component} from "react";
import {connect} from "react-redux";
import {enableCalls} from "redux-call";
export const COMPONENT_ID = "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:
import {dispatch} from "store";
import {call} from "redux-call";
import {COMPONENT_ID} from "MyAwesomeComponent.js";
let playMediaAction = call(COMPONENT_ID, {method: "playMedia"});
let seekMediaAction = call(COMPONENT_ID, {method: "seekMedia", args: [10]});
let getCurrentTimeAction = call(COMPONENT_ID, {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 |