์๋์จ์ผ์์ ๋ง๋ ์ ์ญ ์ํ๊ด๋ฆฌ ๋๊ตฌ
์ง๊ธ๊น์ง ๋ฐฐ์ด decorator, metadata๋ฅผ ํ์ฉํ๋ ๊ฒ์ด ํน์ง!
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
๊ธฐ์กด์ TSyringe + reflect-metadata๋ฅผ ์ฌ์ฉํ์ฌ ๋ง๋ ๊ฐ๋จํ ์คํ ์ด๋ฅผ usestore-ts
๋ฅผ ์ฌ์ฉํ์ฌ ๋ง์ด๊ทธ๋ ์ด์
ํด๋ณด์.
usestore-ts์์ ์ ๊ณตํ๋ Store ๋ฐ์ฝ๋ ์ดํฐ๋ ๊ธฐ์กด ObjectStore ํด๋์ค๋ฅผ ๋์ฒดํ๋ค.
์ฆ, ObjectStore๊ฐ ์ ๊ณตํ๋ ๊ธฐ๋ฅ (๊ตฌ๋
๊ด๋ฆฌ, ์ํ๋ณ๊ฒฝ์ ์๋ฆฌ๋ ์์
๋ฑ)์ ๋ด๊ณ ์๋ค๋ ๊ฒ
import { singleton } from 'tsyringe';
import { Store, Action } from 'usestore-ts';
/*
* ์ฑ๊ธํค ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์คํ ์ด ๋ฐ์ฝ๋ ์ดํฐ ๋ณด๋ค ์์์ ๋์.
* ์ฑ๊ธํค์ ๋จน์ ํด๋์ค๋ฅผ ์คํ ์ด ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ๋ฉด ์ด์๊ฐ ์์ ์ ์์
*/
@singleton()
@Store()
export default class CounterStore {
counter = 0;
// ์ก์
๋ฐ์ฝ๋ ์ดํฐ๋ publish ๋ฉ์๋๋ฅผ ๋จธ๊ธ๊ณ ์๋ค.
@Action()
increase(step = 1) {
this.counter += step;
}
@Action()
decrease(step = 1) {
this.counter -= step;
}
}
usestore-ts๊ฐ ์ ๊ณตํ๋ useStore ํ
์ผ๋ก ๊ธฐ์กด useObjectStore๋ฅผ ๋์ฒด
forceUpdate ๋ฆฌ์ค๋๋ฅผ ๋จธ๊ธ๊ณ ์๋ค.
import { container } from 'tsyringe';
import { useStore } from 'usestore-ts';
import CounterStore from '../stores/counterStore';
export default function useCounterStore() {
const store = container.resolve(CounterStore);
return useStore(store);
}
useStore(store)๋ [state, store]
ํํ์ ๊ฐ์ ๋ฐํํ๋ค.
state๋ก ์คํ ์ด์ ๋ด๊ธด ๊ฐ๋ค์ ์ฌ์ฉ
store๋ ์คํ ์ด์ ๋ด๊ธด ์ก์
api๋ค์ด ๋ด๊ฒจ ์๋ค.
import useCounterStore from '../hooks/useCounterStore';
export default function CounterController() {
const [, store] = useCounterStore();
const handleClickIncrease = (step?: number) => () => {
store.increase(step);
};
const handleClickDecrease = (step?: number) => () => {
store.decrease(step);
};
return (
<div>
<button type="button" onClick={handleClickIncrease(10)}>
Increase 10
</button>
<button type="button" onClick={handleClickIncrease()}>
Increase
</button>
<button type="button" onClick={handleClickDecrease(10)}>
Decrease 10
</button>
<button type="button" onClick={handleClickDecrease()}>
Decrease
</button>
</div>
);
}
import useCounterStore from '../hooks/useCounterStore';
export default function Counter() {
const [{ counter }] = useCounterStore();
return (
<div>
<p>{`counter: ${counter}`}</p>
</div>
);
}