해당 포스팅은 Apllo Hooks로 React 앱 개발하기 포스팅을 참고하여 작성하였습니다. 유익한 포스팅과 지식 공유에 대해 감사드립니다.
Apollo Hooks
란graphql
통신에서 활용되는 Apollo-Client
기능 중에 하나이며, useQuery
/ useMutation
같은 메서드를 제공하고 쿼리를 다루는 기능이라 할 수 있다.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>
)
}
Query
통신을 비동기적으로 배치해야할 경우 네번째 속성으로 추가하여 활용할 수 있따.const {loading, error, data, fetchMore} = useQuery(...);
...
const handleClick = async() => {
const data = await fetchMore();
console.log(data);
}
useMutaion
함수의 경우 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] },
})
},
})