@redneckz/react-dispatcher
v0.0.6
Published
React global action bus
Downloads
7
Readme
react-dispatcher
TODO
Installation
npm install --save @redneckz/react-dispatcher
How-to
import React from 'react';
import { useDispatcher } from '@redneckz/react-dispatcher';
const initialState = { count: 1000 };
/**
* Local store. No need in "Lifting state up"
*/
function reducer(state, { type }) {
switch (type) {
case 'INC':
return { count: state.count + 1 };
case 'DEC':
return { count: state.count - 1 };
default:
return state;
}
}
export function Counter() {
const [state, dispatch] = React.useReducer(reducer, initialState);
const dispatcher = useDispatcher(state, dispatch);
return (
<button onClick={() => dispatcher({ type: 'INC' })}>{state.count}</button>
);
}
import { useDispatcher } from '@redneckz/react-dispatcher';
/**
* Some container far away from counter
* and loosely coupled with containers
* that support pattern { type: "dec" }
*/
export function Dec() {
const dispatcher = useDispatcher();
return <button onClick={() => dispatcher({ type: 'DEC' })}>-</button>;
}
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import { useDispatcher, applyMiddleware } from '@redneckz/react-dispatcher';
/**
* Produces new hook useDispatcher
*/
export default applyMiddleware(
logger,
thunk,
)(useDispatcher);