create account

[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기 by anpigon

View this thread on: hive.blogpeakd.comecency.com
· @anpigon · (edited)
$1.54
[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기
이전글 [**"\[React\] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"**](/zzan/@anpigon/react-native-manage-application-state-with-mobx-state-tree-3)에서 이어지는 내용입니다. 참고로 이 포스팅은 제가 학습한 내용을 노트에 정리하듯이 기록하여 올리는 글이기 때문에 보팅 안해주셔서 됩니다.  많은 분들이 코딩에 흥미를  느꼈으면 좋겠습니다.  ㅋ

<br>

***

![](https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png)
* 출처: https://egghead.io/courses/manage-application-state-with-mobx-state-tree
***

<br>

# Derive Information from Models Using Views

> 강의 링크: https://egghead.io/lessons/react-derive-information-from-models-using-views

4번째 레슨입니다. 이번 레슨에서는 데이터를 선언적으로 derive하고 캐싱하는 views 사용 방법에 대해 학습합니다.

<br>우리는 다음을 배우게 됩니다.

*  모델에서 views를  introduce하는 방법.
* 계산된 값(computed properties)은 Mobx computed fields에 의해 작동.
* `reaction ` 처럼 MST를 Mobx 유틸리티와 결합(combine)하는 방법

<br>

***

<br>

WhishList 모델에 총 가격(totalPrice) 필드를 추가합니다.

`src/models/WhishList.js`
```
const WishList = types
  .model({
    items: types.optional(types.array(WishListItem), []),
    totalPrice: types.number, // add here
  })
```

하지만 이렇게 사용하면 WishList 모델이 변경될 때마다 `totalPrice`를 매번 계산해야합니다. 

그래서 다음과 같이 views를 사용합니다. views 이미 계산된 값을 캐싱합니다. 그래서 `item`이 추가되거나 `price` 가 변경되지 않으면 `totalPrice`를 다시 계산하지 않고 캐싱하고 있는 값을 리턴합니다.  

```
export const WishList = types
  .model({
    items: types.optional(types.array(WishListItem), [])
    // totalPrice: types.number,
  })
  .views(self => ({
    get totalPrice() {
      return self.items.reduce((sum, entry) => sum + entry.price, 0);
    }
  }))
```

<br><br>

# 모델의 view 테스트 하기

다음과 같이 `WhishList.test.js`에 테스트 케이스를 작성합니다. 

`src/models/WhishList.test.js`

```
it("can calculate the total price of a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "Chesterton",
        price: 7.35
      },
      {
        name: "Book of G.K. Chesterton",
        price: 349.95
      }
    ]
  });

  expect(list.totalPrice).toBe(357.3);
});
```

<br><br>

# reaction 사용하여 모델의 view 테스트 하기

mobx에서 제공하는 `reaction` 유틸은 모델의 데이터 변화를 감지합니다. 모델에 변화가 발생하였을때 `totalPrice` 값의 변화를 살펴봅시다.

```
import { reaction } from 'mobx';

it("can calculate the total price of a wishlist", () => {
  // ...
 
  let changed = 0;
  // totalPrice 변화가 발생하면 changed 증가
  reaction(() => list.totalPrice, () => changed++); 
  
  expect(changed).toBe(0); // 변화 없음
  console.log(list.totalPrice);
  list.items[0].changeName("Test"); // 이름 변경
  expect(changed).toBe(0); // 변화 없음
  list.items[0].changePrice(10); // 가격 변경
  expect(changed).toBe(1); // 계산됨
});
```
위 테스트를 수행해보면 `price` 값에 변화가 발생하였을때만, `totalPrice`가 동작하는 것을 확인할 수 있습니다.



<br>오늘 수업 끝.
***

<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-4). Steem blog powered by [ENGRAVE](https://engrave.website).</sup></center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 55 others
properties (23)
authoranpigon
permlinkreact-native-manage-application-state-with-mobx-state-tree-4
categoryzzan
json_metadata{"format":"markdown","app":"busy/2.5.6","tags":["zzan","kr","kr-dev","dev","busy","jjm"],"image":["https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png","https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png"],"links":["https://egghead.io/courses/manage-application-state-with-mobx-state-tree","https://egghead.io/lessons/react-derive-information-from-models-using-views","https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg'%3E%3Ch5%3Evote,"],"engrave":{"domain":"anpigon.dblog.org","permlink":"react-native-manage-application-state-with-mobx-state-tree-4","url":"https://anpigon.dblog.org/react-native-manage-application-state-with-mobx-state-tree-4","featured_image":"https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png","categories":["5d8b1dc94302ae00124415b9"]},"community":"busy","good":true}
created2019-08-20 02:29:36
last_update2019-09-30 14:37:48
depth0
children5
last_payout2019-08-27 02:29:36
cashout_time1969-12-31 23:59:59
total_payout_value1.195 HBD
curator_payout_value0.342 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,282
author_reputation17,258,940,000,931
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,725,841
net_rshares4,702,065,572,769
author_curate_reward""
vote details (119)
@anpigon ·
응원해주시는 모든 분들께 감사합니다. ㅎㅎ
properties (22)
authoranpigon
permlinkpwixj3
categoryzzan
json_metadata{"tags":["zzan"],"app":"steemzzang/0.1"}
created2019-08-20 07:16:15
last_update2019-08-20 07:16:15
depth1
children0
last_payout2019-08-27 07:16:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length23
author_reputation17,258,940,000,931
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,732,492
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/kr-newbie/avatar) [kr-newbie](/@kr-newbie)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[kr-newbie](/@kr-newbie)님의 [[8/20 kr-newbie 큐레이팅 프로젝트]](/zzan/@kr-newbie/8-20-kr-newbie) <br /> 

 <blockquote>...b.io/#/wallet/kr-newbie
happigon에서 자세한 임대내역이 확인 가능합니다.
만들어주신 anpigon께 감사드립니다! 
<ul>
<li>anpigon님의 HAAPIGON 유저가이드를 참고해주시기 바랍니다!</...</blockquote>
👍  
properties (23)
authorsteem.apps
permlinkre---------react-native-manage-application-state-with-mobx-state-tree-4-20190820t110615244z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-20 11:06:15
last_update2019-08-20 11:06:15
depth1
children0
last_payout2019-08-27 11:06:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length414
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,739,269
net_rshares3,800,257,037
author_curate_reward""
vote details (1)
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/wonsama.zzan/avatar) [wonsama.zzan](/@wonsama.zzan)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[wonsama.zzan](/@wonsama.zzan)님의 [[ZZAN] DAILY REPORT 2019-08-20](/zzan/@wonsama.zzan/zzan-daily-report-2019-08-20) <br /> 

 <blockquote>...td>
<td>[Movie 리뷰] 숨은 진주같은 한</td>
<td>28</td>
</tr>
<tr>
<td>anpigon/td>
<td>11:29:36</td>
<td>[React]  Mobx-state-</td>
<td>6</t...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-manage-application-state-with-mobx-state-tree-4-20190820t153606028z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-20 15:36:06
last_update2019-08-20 15:36:06
depth1
children0
last_payout2019-08-27 15:36:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length450
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,751,506
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/blockchainstudio/avatar) [blockchainstudio](/@blockchainstudio)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[zzan1004](/@zzan1004)님의 [ALL IN ONE CLAIM](/zzan/@zzan1004/all-in-one-claim#@blockchainstudio/re-zzan1004-all-in-one-claim-20190820t154857784z) <br /> 

 <blockquote> 이번에도 anpigon 멋진 기능 추가하셨군요. 사실 관련포맷나왔을때 스엔에서 알아서 기능을 넣을 줄 알았는데 아직도 안되고 있었군요ㅠㅠ 참고로 이전에 scotauto도 한번에 처리하는 방식으로 바뀌었습니다.
참고로 딜레이는 ...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-manage-application-state-with-mobx-state-tree-4-20190820t154907318z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-20 15:49:09
last_update2019-08-20 15:49:09
depth1
children0
last_payout2019-08-27 18:47:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length487
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,751,891
net_rshares0
@virus707 ·
Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.
properties (22)
authorvirus707
permlinkre-react-native-manage-application-state-with-mobx-state-tree-4-1566324109
categoryzzan
json_metadata{"tags":["jjm"]}
created2019-08-20 18:01:48
last_update2019-08-20 18:01:48
depth1
children0
last_payout2019-08-27 18:47:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length203
author_reputation557,563,606,581,756
root_title"[React] Mobx-state-tree 학습하기 #4 : Views를 사용하여 모델에서 정보 보여주기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,756,206
net_rshares0