Create initial state & reducers
// reducer.js
import { combineReducers } from "lib";
const store1 = {
a: '1',
b: '2'
};
const store2 = {
c: 'c',
d: 'd',
};
const reducer1 = (state: any, action: any) => {
switch (action.type) {
case 'SETA':
return {
...state,
a: action.payload
};
default:
return state;
}
};
const reducer2 = (state: any, action: any) => {
switch (action.type) {
case 'SETC':
return {
...state,
c: action.payload
};
default:
return state;
}
};
export const states = {
store1,
store2,
};
export const reducers = combineReducers({
store1: reducer1,
store2: reducer2,
});
Create a store
import { createStore } from 'lib';
import { states, reducers } from './reducer';
const { useStore, connect } = createStore(reducers, states)
export { useStore, connect };
Usage
const Foo = () => {
const [store, dispatch] = useStore();
const [storeA, dispatchA] = useStore('store1');
const handleChange = () => {
dispatchA({
type: 'SETA',
payload: 'hello',
});
dispatch(({getState, dispatch}) => {
console.log(getState());
// some async function call...
});
};
return (
<div>
<div>{store.store1.a}</div>
<div>{storeA.b}</div>
</div>
);
}
Read & update state in a class component
class Foo extends React.Component {
//...
handleChange = () => {
const {store, dispatch} = this.props;
// ...
}
render () {
// ...
}
}
// If you omit the second param (store name),
// Foo will be connected to the entire store.
export default connect(Foo, 'store1');