기본 콘텐츠로 건너뛰기

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는 처음엔 다소 어색하지만 한번 맛들이면 빠져나오기 힘들다. 일관적인 구현을 위해 적극적으로 사용하자.

댓글

이 블로그의 인기 게시물

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

저지연 오디오 생성 LLVC 사용기

https://github.com/KoeAI/LLVC 써봄 CUDA 11.8 버전 쓰고 있어 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 VC 없어서 설치 https://wikidocs.net/168848 참조 FAIRSEQ 관련 오류 https://github.com/facebookresearch/fairseq/issues/2908 pip install editdistance  설치 No CUDA runtime is found, using CUDA_HOME='C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' 오류 멀쩡하게 있는데 안됨. pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio==2.1.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118 다시 설치 set DISTUTILS_USE_SDK=1 이게 문젠가 설정하고 재도전 Using cached ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl (118 kB) Building wheels for collected packages: fairseq   Building wheel for fairseq (pyproject.toml) ... error   error: subprocess-exited-with-error   × Building wheel for fairseq (pyproject.toml) did not run successfully.   │ exit code: 1   ╰─> [1829 lines of output]       No CUDA runtime is found, usi...