0.2.6 • Published 9 months ago
shalala v0.2.6
shalala
Easy state management for react using hooks in less than 1kb.
Table of Contents
Install:
npm i shalala
or
yarn add shalala
Minimal example:
import { createStore } from 'shalala';
const initialState = {
counter: 0,
another: 100
};
const actions = {
// Using store.setState
increment: (store, amount) => {
store.setState(state => ({
counter: state.counter + amount
}));
},
// Using custom set state function
decrement: (_, amount) => {
return (state) => ({
counter: state.counter - amount
})
},
reset: () => ({
counter: 0
})
};
const mapStateToProps = (state) => ({
counter: state.counter
})
const useCounterStore = createStore(initialState, actions);
const Counter = () => {
const [state, actions] = useCounterStore(mapStateToProps);
return (
<div>
<p>
Counter:
{ state.counter }
</p>
<button type="button" onClick={() => actions.increment(1)}>
+1 to global
</button>
{ ' ' }
<button type="button" onClick={() => actions.decrement(1)}>
-1 to global
</button>
<button type="button" onClick={() => actions.reset()}>
reset
</button>
</div>
);
};
export default Counter
Nested states:
import { createStore } from 'shalala';
const counterState = {
state: () => ({
value: 0
}),
actions: {
// Using store.setState
increment: (store, amount) => {
store.setState(state => ({
...state,
counter: {
value: state.counter.value + amount
}
}));
},
// Using custom set state function
decrement: (_, amount) => (state) => ({
...state,
counter: {
value: state.counter.value - amount
}
}),
reset: () => (state) => ({
...state,
counter: {
value: 0
}
})
}
}
const randomState = {
state: {
value: 0
},
actions: {
generate: () => state => ({
...state,
random: {
value: state.random.value + Number(Math.random().toFixed(4))
}
})
}
}
const initialState = {
counter: counterState,
random: randomState
};
const mapCounterState = (state) => state.counter;
const mapCounterActions = (actions) => actions.counter;
const useStore = createStore(initialState);
const Counter = () => {
const [state, actions] = useStore(mapCounterState, mapCounterActions);
console.log(state, actions)
return (
<div>
<p>
Counter: { ' '}
{ state.value }
</p>
<button type="button" onClick={() => actions.increment(1)}>
+1 to global
</button>
{ ' ' }
<button type="button" onClick={() => actions.decrement(1)}>
-1 to global
</button>
{ ' '}
<button type="button" onClick={() => actions.reset()}>
reset
</button>
</div>
);
};
const mapRandomState = (state) => state.random;
const mapRandomActions = (actions) => actions.random;
const Random = () => {
const [state, actions] = useStore(mapRandomState, mapRandomActions);
return (
<div>
<p>
Value: { ' '}
{ state.value }
</p>
<button type="button" onClick={() => actions.generate()}>
Generate
</button>
</div>
);
};
const Nested = () =>{
return (
<div>
<Counter />
<Random />
</div>
)
}
export default Nested