query에 id를 요청해야 cache에 저장된다.
seeProfile Query는 params로 전달된 username으로 해당 user의 정보를 준다.
seeProfile Query에서 id 요청 유무를 비교해보자.
const SEE_PROFILE_QUERY = gql`
query seeProfile($username: String!) {
seeProfile(username: $username) {
firstName
lastName
username
bio
avatar
photos {
...PhotoFragment
}
...
`;
Profile component를 만들고
/users/jw
url로 이동해서 InMemoryCache를 확인해봤는데 seeProfile Query가 안보인다.다만 Root Query에 저장되어있었다. 이건 cache에 저장된 것이 아니다.
cache는 User:1
이런식으로 저장되어있어야 한다.
const SEE_PROFILE_QUERY = gql`
query seeProfile($username: String!) {
seeProfile(username: $username) {
id
firstName
lastName
username
bio
avatar
photos {
...PhotoFragment
}
...
`;
짠 user id 1의 profile에 들어가니까
User:1
cache가 생겼다 🥳
keyFields: 고유 식별자(unique)로 설정해줄 필드 명시
id말고 다른 필드를 고유 식별자로 설정하고 싶을 때가 있다.
실제로 seeProfile 쿼리는 고유 식별자를 id가 아니라 username으로 둔다.
id밖에 모르는 apollo를 위해 keyFields
를 따로 커스텀 정의해줄 필요가 있다.
cache 정의하는 부분에 typePolicies
User의 keyFields는 storedObject를 받아서 고유식별자를 반환한다.
cache: new InMemoryCache({
typePolicies: {
User: {
keyFields: (obj) => `User:${obj.username}`,
},
},
}),
cache가
User:username
으로 바뀌었다!
그 전엔 구구절절하던 ROOT_QUERY의 seeProfile 쿼리도 ref만 저장하게 됐다.
update함수의 cache를 출력해서 InMemoryCache를 확인할 수 있지만,
useApolloClient로 볼 수도 있다.
const client = useApolloClient();