Apollo Hooks

손병진·2021년 2월 21일
0

해당 포스팅은 Apllo Hooks로 React 앱 개발하기 포스팅을 참고하여 작성하였습니다. 유익한 포스팅과 지식 공유에 대해 감사드립니다.

Apollo Hooks

  • Apollo Hooks
    graphql 통신에서 활용되는 Apollo-Client 기능 중에 하나이며, useQuery / useMutation 같은 메서드를 제공하고 쿼리를 다루는 기능이라 할 수 있다.

useQuery

  • graphql 통신으로 데이터를 받을때 활용하는 메서드로 프로미스 객체를 리턴한다.
// 쿼리 작성
const GET_CONTINENTS = gql`
  query {
    continents {
      code
      name
    }
  }
`

// useQuery 활용
function Continents() {
  const { loading, error, data } = useQuery(GET_CONTINENTS)
  // 세가지 속성을 받을 수 있으며, 프로미스 값에 따라 로딩, 에러, 데이터 값을 받는다.
  // 그렇기 때문에 Hooks 를 활용하지 않거나 비동기적으로 처리할 경우, 
  // async/await 문법과 같이 활용될 수 있다.
  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!(</p>
  return (
    <ul>
      {data.continents.map(({ code, name }) => (
        <li key={code}>{name}</li>
      ))}
    </ul>
  )
}
  • fetchMore
    만약 Query 통신을 비동기적으로 배치해야할 경우 네번째 속성으로 추가하여 활용할 수 있따.
const {loading, error, data, fetchMore} = useQuery(...);
...                                                  
const handleClick = async() => {
  const data = await fetchMore();
  console.log(data);
}

useMutaion

  • useMutaion 함수의 경우 useQuery 처럼 객체를 리턴하는 것이 아니라, 배열을 리턴한다.
    배열의 첫번째 요소는 mutation 쿼리를 호출하는 함수이고,
    배열의 두번째 요소는 useQuery 리턴값과 같은 객체이다.
    데이터에 대하여 수정을 가할 때 활용한다.
// mutation 쿼리 작성(이런식으로 인자를 설정하여 보낼 수도 있다)
export const ADD_NOTE = gql`
  mutation addNote($content: String) {
    addNote(content: $content) {
      id
      content
    }
  }
`

// useMutation 활용
/* arguments 로 들어가는 쿼리 이외의 update 와 같은 설정은
   추가된 데이터가 바로 UI에 반영될 수 있도록 하는 것으로 자세한 설명을 위 포스팅 링크를 참고바란다.*/
const [addNote, { loading, error }] = useMutation(ADD_NOTE, {
  update(cache, { data: { addNote } }) {
    const { notes } = cache.readQuery({ query: GET_NOTES })
    cache.writeQuery({
      query: GET_NOTES,
      data: { notes: [...notes, addNote] },
    })
  },
})
profile
https://castie.tistory.com

0개의 댓글