기본 콘텐츠로 건너뛰기

vulcanJS - 부록 Appendix A. Mutation (delete) 보강

Posts를 만들면서 약간 아쉬웠던 부분은 Delete 부분에 대해서 너무 SmartForm에 의지하여 간단하게 넘어가긴 했다.
showRemove={true}
옵션을 통해 한줄 찍 긋고 Delete라고 나오는 부분을 클릭하는 것도 좋지만
목록에서 지우거나 상세 보기에서 지울 일도 분명 있을 것이다.

역시나 이것도 목록(ex. withList)을 가져올 때 처럼 HoC(Higher-Order Component)를 사용한다.
http://docs.vulcanjs.org/mutations.html#Remove-Mutation 부분을 참조하자.

이번에 구현할 것은 목록마다 remove 버튼을 달고 버튼을 누르면 이벤트를 받아 삭제하도록 구현해보자.
import { registerComponent, withList, withRemove } from 'meteor/vulcan:core';
먼저 해야할 것은 withRemove를 import에 추가하는 것이다.
그러면 withRemove를 registerComponent시 사용할 수 있다.
withList와 함께 withRemove도 추가하자.
registerComponent('PostsListComponent', PostsListComponent, [
  withList, {
    collection: Posts
  }], [
  withRemove, {
    collection: Posts
  }
]);
withRemove도 withList와 동일하게 collection만 지정하면 된다.
준비는 다 되었다. withRemove를 붙여서 this.props는 removeMutation을 갖게 되었다.
removeMutation의 사용법은 다음과 같다.
this.props.removeMutation({
  documentId: documentId
}).then(/* success */).catch(/* error */);
promise를 지원한다. 오류처리는 catch에 정상적 완료 후에 무언가를 하려면 then에 function을 구현하자.
지금은 별 생각이 없으므로 버튼을 만들고 단순하게 붙여보자.
                <button onClick={()=>this.props.removeMutation({
                    documentId: o._id
                  })
                  .then(console.log)
                  .catch(console.log)
                }>Remove</button>
이런 버튼을 붙이면 되겠다.

전체 소스를 다시 살펴보자. PostsListComponent는 이렇게 되었다.
import React, { Component } from 'react';
import { Link } from 'react-router';
import { registerComponent, withList, withRemove } from 'meteor/vulcan:core';
import Posts from "../modules/posts/collection.js";
class PostsListComponent extends Component {
  render () {
    return (
      <div>
        {
          this.props.results
            && this.props.results.map(o=>
              <div key={o._id}>
                <Link to={`/posts/${o._id}`}>{o.title}</Link>
                <button onClick={()=>this.props.removeMutation({
                    documentId: o._id
                  })
                  .then(console.log)
                  .catch(console.log)
                }>Remove</button>
              </div>
            )
        }
      </div>
    );
  }
}
registerComponent('PostsListComponent', PostsListComponent, [
  withList, {
    collection: Posts
  }], [
  withRemove, {
    collection: Posts
  }
]);
export default PostsListComponent;
목록 한건한건 오른쪽 끝에 Remove버튼이 붙었고 누르자마 해당 Post가 지워진다.
HoC는 처음엔 다소 어색하지만 한번 맛들이면 빠져나오기 힘들다. 일관적인 구현을 위해 적극적으로 사용하자.

댓글

이 블로그의 인기 게시물

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.