react-combine-provider
v0.1.3
Published
Combine react providers in ease
Downloads
3,989
Maintainers
Readme
React Combine Provider
Combine react providers in ease
Requires React >= 16.8.0
Fully support unstated-next and constate
Install
npm install --save react-combine-provider
Usage
- unstated
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { createContainer } from 'unstated-next';
import { combineProviders } from 'react-combine-provider';
const useCounter1 = (initialState = 1) => {
const [count, setCount] = useState(initialState);
const decrement = () => setCount(count - 1);
const increment = () => setCount(count + 1);
return { count, decrement, increment };
};
const Counter1 = createContainer(useCounter1);
const useCounter2 = (initialState = 2) => {
const [count, setCount] = useState(initialState);
const decrement = () => setCount(count - 2);
const increment = () => setCount(count + 2);
return { count, decrement, increment };
};
const Counter2 = createContainer(useCounter2);
function CounterDisplay1() {
const counter1 = Counter1.useContainer();
console.log('rendering');
return (
<div>
<div>counter display 1</div>
<div>counter 1</div>
<button onClick={counter1.decrement}>-</button>
<span>{counter1.count}</span>
<button onClick={counter1.increment}>+</button>
<br />
</div>
);
}
function CounterDisplay2() {
const counter1 = Counter1.useContainer();
const counter2 = Counter2.useContainer();
return (
<div>
<div>counter display 2</div>
<div>counter 1</div>
<button onClick={counter1.decrement}>-</button>
<span>{counter1.count}</span>
<button onClick={counter1.increment}>+</button>
<div>counter 2</div>
<button onClick={counter2.decrement}>-</button>
<span>{counter2.count}</span>
<button onClick={counter2.increment}>+</button>
<br />
</div>
);
}
const StateProviders = combineProviders([
[Counter1.Provider, { initialState: 5 }],
Counter2.Provider,
]);
function App() {
return (
<StateProviders>
<CounterDisplay1 />
<br />
<CounterDisplay2 />
</StateProviders>
);
}
ReactDOM.render(<App />, document.getElementById('root'));