[React] Mobx-state-tree 학습하기 #1 : Mobx-state-tree를 사용해서 Reat State 관리하기
zzan·@anpigon·
0.000 HBD[React] Mobx-state-tree 학습하기 #1 : Mobx-state-tree를 사용해서 Reat State 관리하기
안녕하세요. 안피곤입니다.
저는 최근에 mobx-state-tree를 열심히 공부하고 있습니다. 제이콥님이 알려주신 Mobx는 너무 매력적입니다. 그래서 학습 중이던 Redux, Redux-Thunk, Redux-Saga를 그만두고, Mobx 동영상 강의를 찾아서 열심히 배우고 있습니다. 개발자에게 기술 공부는 끝이 없습니다. 기술 트렌드는 매년 바뀝니다. 그리고 유투브에는 새로운 무료 강의가 계속 업로드되고 있습니다.
저는 작년부터 Front-End, Node.js, React 세계에 발 담그면서 새로운 기술을 계속 공부하고 있습니다. 매일매일 새로운 기술이 쏟아져 나오고 있고, 새로운 기술들은 또 저에게 신선함을 안겨줍니다. 새로운 기술을 처음 배울때는 어렵지만, 이 기술에 익숙해지고 나면 그 다음 개발할 때는 매우 편합니다.
<br>
<br>
***
<br>
<br>

* 출처: https://egghead.io/courses/manage-application-state-with-mobx-state-tree
<br>
이 레슨은 위시리스트 앱을 만드는 과정을 안내합니다. 그리고 우리는 mobx-state-tree(MST)의 핵심 모델을 살펴볼 것입니다. 모델(Model)은 상태(state)의 형태(shape)을 정의하고 타입 유효성 검사를 수행합니다.
우리는 다음을 배우게 됩니다.
* `types.Model`를 사용하여 모델을 정의하기
* `Model.create`를 사용하여 JSON에서 모델 인스턴스화하기
* Primitive types : `types.string` 와 `types.number`
* Type inference for primitive types
* `types.array`
* `types.optional`
* Composing models into a model tree
<br>
***
<br>
# mobx-state-tree(MST) Models를 사용하여 어플리케이션 도메인 정의하기

<br>
## wishlist 프로젝트 생성하기
우선 React App 프로젝트를 생성합니다.
```
$ npx create-react-app wishlist
```
<sup>([**npx**](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b)는 npm 5.2+ 이상 부터 사용가능합니다. 이전 버전을 사용중이라면 ["instructions for older npm versions"](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f) 문서를 참고하세요.)</sup>
<br>아래와 같이 필요한 모듈이 설치되면서 프로젝트가 생성됩니다.

## Mobx 모듈 설치하기
다음 명령어를 입력하여 mobx와 mobx-state-tree 모듈을 설치합니다.
```
$ yarn add mobx mobx-react mobx-state-tree
```
<br>아래 화면처럼 설치가 진행됩니다.

<br>
## model 생성하기
`./src` 폴더 아래에 `model` 폴더를 생성합니다.

<br>그리고 `WhishList.js` 파일을 생성합니다.

<br>`WhishList.js` 파일에는 다음 내용을 입력합니다.
```js
// src/models/WhishList.js
import { types } from "mobx-state-tree";
// WishListItem 모델 정의
export const WishListItem = types.model({
name: types.string,
price: types.number,
image: types.optional(types.string, ""),
});
// WishList 모델 정의
export const WishList = types.model({
items: types.optional(types.array(WishListItem), [])
});
```
<br>`WishListItem`의 `image` 속성은 **optional**이며 기본값은 `""`입니다. 그리고 `image`를 아래와 같이 입력할 수도 있습니다.
```
export const WishListItem = types.model({
// ...
image: ""
});
```
<br>
<br>
# WhishList 모델 테스트 하기
`WhishList.test.js` 파일을 생성합니다.

<br>`WhishList.test.js` 파일에는 다음 내용을 입력합니다.
```
import { WishListItem, WishList } from "./WhishList";
it("can create a instance of a model", () => {
const item = WishListItem.create({
name: "Reat Native - anpigon",
price: 28.73
});
expect(item.price).toBe(28.73);
expect(item.image).toBe("");
});
it("can create a wishlist", () => {
const list = WishList.create({
items: [
{
name: "Reat Native - anpigon",
price: 28.73
}
]
});
expect(list.items.length).toBe(1);
expect(list.items[0].price).toBe(28.73);
});
```
<br>
테스트 하기 위해서 `yarn test`를 입력합니다.

테스트에 성공하면 다음과 같은 메세지가 콘솔에 출력됩니다.

<br>
<br>
`댓글`, `팔로우`, `좋아요` 해 주시는 모든 분께 감사합니다.
항상 행복한 하루 보내시길 바랍니다.
***
<center><img src='https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg'><h5>vote, reblog, follow <code><a href='/@anpigon'>@anpigon</a></code></h5></center>
***
<center><sup>Originally posted on [안피곤님의 블로그](http://anpigon.dblog.org/react-native-manage-application-state-with-mobx-state-tree-1). Steem blog powered by [ENGRAVE](https://engrave.website).</sup></center>👍 philhyuntd, zzan.biz, astraea09, china.mobile, cn-news, china-unicom, everrich, erke, cnpc, cn-times, cn-reporter, cazbu, zyj, fty, donasteem, elviento, krwhales, deepinside, deepdown, sf1, flit, fun2learn, ulockblock, nailyourhome, delegate4upvot, accelerator, bert0, talken, wangpigon, steemory, pigoncchio, pediatrics, songbj, imrahelk, minigame, nympheas, kudock, wonsama, realmankwon, realmankwon.scot, doctor.strange, guro, shindorim, sumimasen, freefee, tongdak, superguard, kpay, sneack, gzone, betamonsters, technomart, postme, o0o0o, thecards, beanpole, prettyguy, goblinsorcerer, lyannaforest, lightangel, krnews, wbot01, dead.pool, black.widow, marvel.spiderman, marvel.hulk, marvel.ironman, black.pan.ther, claim7, wcasino, wcasino.pay, wcasino.holdem, wcasino.jackpot, steemit.holdem, steemit.jackpot, smcard, smonsmon, yongsan, incheon, mapo, shingil, checkname, starterpack, gdragon, smtester, showdown, monstersteem, freesale, testsama, kimch, hanbok, jjangjjangman, yawang, roadmap, adultbaby, ppororo, lotto645, alphamonsters, girlfriends, fastway, smonsang, lastsmon, smilezone, bearbaby, developments, originals, oilbank, iliili, kotlin, flutters, gamemonsters, blueguy, sicbo, yaoi, farmfarm, giantroc, koboldminer, crustaceanking, waterelemental, ragingimpaler, animatedcorpse, spiritforest, serpentflame, goblincaptain, divineknight, feralwarrior, elementalair, jestertwisted, bansheescreaming, skyselenia, darknesslord, naturalyanna, astormbringer, giantfrost, warriorminotaur, golemalric, orcelemental, spiritpriest, lordjester, magifirestorm, muhan, smseller, lovelyyeon.cur, done.mod, skysung, stylegold, ukk, ai-channel, newbijohn, j-car, imisstheoldkanye, laissez-faire, anpigon, reportup, steem.apps, zzan.co20, eversloth, floridasnail, zzan-m, sct.cu10, leems, tiamo1, cn-sct, jjy, andrewma, ravenkim, lucky2.aaa, stpeople, sleeprince, zzan.adv, jacobyu, kiwifi, happyberrysboy, glory7, wjs, roadofrich, virus707, zzan.co13, zzangu, honeybeerbear, skan, hodolbak-zzan, trips.teem, hyokhyok, wonsama.zzan, zzan.co3, son10001, zzan.co10, rainingfall, dodoim, zzan1004, son1001, gghite.zzan, zzan.blue, ratticus, hykwf678233, blockchainstudio, rokairforce, elraberscer, mcenoramle, gouji, steem-ua, sargoon, storysharing, ziq, moby.dick, parisfoodhunter, verifyme, steemconductor, windmolen, boftea, steemnara, rubberducky1004, herobear, zzan.co7, rachman-jr25, gmarket, alimehdi244, cjsdns, omerbiabdulah,