Apollo Cache Update

roglog·2021년 2월 18일
0

Cache


  • Apollo Client는 graphQL qurey들을 cache에 저장한다.

Update Cache


  • cache를 업데이트하는 방법에는 크게 2가지 방법이 있다.
  1. cache를 직접 update

  2. query를 refetch

    1. Cache를 직접 Update


    • writeFragment를 사용하여 cache의 일부분을 바꾼다.
    • Ex)
    const client = useApolloClient()
    client.writeFragment({
        id: `User: ${id}`,
        fragment: gql`
            fragment EditUser on User {
                email
            }
        `
        data: {
            email: newEmail,
        }
    
    })

    2. Query를 Refetch


    1) useQuery에서 refetch
    • useQuery에는 'refetch'라는 result property가 존재하여 쿼리를 refetch 할 수 있다.
    • Ex)
      const { { ok }: data, refetch } = useQuery(GET_GREETING, {
            variables: { language: 'english' },
          });
      if(ok) {
          await refetch();
      }
    2) useMutation에서 refetch
    • useMutation에는 refetchQueries이라는 option이 존재하여 쿼리를 refetch 할 수 있다.
    • refetch는 mutation작업이 끝나면 자동으로 일어난다.
    • Ex)
      const [addTodo, { data }] = useMutation(ADD_TODO, {
        refetchQueries: [{ query: TO_DO}],
      }); 
  • 1번 방법은 api를 보내지 않기 때문에 보통 1번 방법이 더 빠름

https://www.apollographql.com/docs/react/caching
https://www.apollographql.com/docs/react/api/react/hooks/#usequery
https://www.apollographql.com/docs/react/api/react/hooks/#usemutation

profile
Full Stack Developer 📚

0개의 댓글