useMutation in apollo Client

이승훈·2023년 2월 7일
0
post-thumbnail

useMutation

apollo Client의 useMutation 훅은 DB의 Data를 mutate하기 위하여 사용하는 Hook이다.

이런저런 방황끝에 알아낸 사용방법을 정리해본다.

반박시 당신말이 맞다.

사용순서는 크게 3단계로 구분된다.

  1. mutate하기 위한 쿼리 작성

    **schema**
    
    createSomething(input: CreateSomethingInput!): somethingIsReturned!
    
    **javascript 내부 코드** 
    
    export const CREATE_SOMETHING = gql`
      mutation CreateSomething($input: CreateSomethingInput!) {
        createomething(input: $input) {
          id
          userId
          groupId
        }
      }

가장 바깥의 mutation CreateSomething($input: CreateSomethingInput!) {}

은 mutation type의 쿼리를 발송한다는 의미이며 useMutation을 사용할 때 variables로 $input을 넣어준다는 의미이다.

유의할점은 $input: CreateSomethingInput! 이부분의 CreateSomethingInput 또한 graphQL내부에서 검증을 하기 때문에 schema에 명시되어있는 올바른 이름으로 입력해야한다.

CreateSomethingInput 내가 요청할 때 보내는 정보!(무언가를 등록할 때 뭐 이름, 나이 이런거)

somethingIsReturned 정상적으로 mutate한 후 돌려받는 정보!(등록한것이 사람이라면 이름, 나이 뭐 이런거)

  1. useMutation 훅을 사용하여 mutate function 얻기

    const [createSomething] = useMutation(CREATE_SOMETHING, {
        context: {
          headers: {
            Authorization:
              'Bearer 토큰토큰토토큰',
          },
        },
        onCompleted: createSomethingComplete,
      });

    위와같이 useMutation 훅을 사용하여 첫번 째 인자로 위에서 작성하였던 쿼리문을 넣어주면 mutate function을 얻을 수 있다.

    두번째 인자부터는 optional한 인자로 위에서 작성된 onCompleted는 mutate가 정상적으로 된 후 돌려받은 값으로 실행할 함수를 지정해주는 것이다.

  2. mutate function을 사용하여 실제 데이터 mutation 하기

try {
    createSomething({
      variables: {
        input: {
          userId: '만드는아이디아이디아아디',
          spec: {만드는 스펙스펙스스펛펙},
          files: [],
        },
      },
    });
  } catch (error) {
      console.log(error);
  }

두번째 단계에서 받은 mutate function의 인자로 첫번째 단계에서 지정해주었던 변수를 넣어 호출하면 실제 mutate를 진행한다.

유의할점은 변수를 보내는 format이다.

profile
Beyond the wall

0개의 댓글