React의 <Link>
태그에서 href는 정적주소만 가능하다. 동적주소는 to를 이용한다.
//Header.js
<Link to={`/users/${data?.me.username}`}>
<Avatar url={data?.me?.avatar} />
</Link>
App.js에서 라우터를 설정해준다. 이 떄 :변수명
을 하면 useParams을 사용하여 넘길 수 있다.
//App.js
<Route path={`/users/:username`}>
<Profile />
</Route>
//Profile.js
import { useParams } from "react-router-dom";
function Profile() {
const { username } = useParams();
return username;
}
export default Profile;
fragment는 다른 query에서 사용가능한 graphql 코드조각이다.
//fragments.js
import { gql } from "@apollo/client";
export const PHOTO_FRAGMENT = gql`
fragment PhotoFragment on Photo{
id
file
likes
totalComments
isLiked
}
`;
사용할 때는 아래와 같이 import한다.
//Home.js
const FEED_QUERY = gql`
query seeFeed {
seeFeed {
...PhotoFragment
caption
createdAt
isMine
user {
username
avatar
}
comments { ...CommentFragment }
}
}
${PHOTO_FRAGMENT}
${COMMENT_FRAGMENT}
`;
graphql에서 id를 제외하고 받아오면 캐시에 저장이 안된다. 왜냐하면 기본적으로 id가 고유식별자로 지정이 되어있기 때문이다.
다른 고유 식별자를 사용하고 싶을 때 apollo cache에 아래와 같이 설정을 해주면 고유식별자로 사용할 수 있다.
//apollo.js
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache({
typePolicies: {
User: {
keyFields: (user) => `User:${user.username}`,
}
}
}),
});
useMutation이나 useQuery를 사용할 때 update와 onClompleted는 cache를 인자로 받느냐 안받느냐의 차이가 있다.
//Profile.js
const unfollowUserUpdate = (cache, result) => {
const { data: { followUser: { ok } } } = result;
if (!ok) {
return;
}
cache.modify({
id: `User:${username}`,
fields: {
totalFollowers(prev) {
return prev - 1;
},
isFollowing(prev) {
return false;
}
}
});
};
const [unfollowUser] = useMutation(UNFOLLOW_USER_MUTATION, {
variables: {
username,
},
update: unfollowUserUpdate
});
하지만 onCompleted에서도 apollo Client를 이용하여 캐시에 접근할 수 있다.
//Profile.js
const client = useApolloClient();
const followUserCompleted = (data) => {
const { followUser: { ok } } = data;
if (!ok) {
return;
}
const { cache } = client
cache.modify({
id: `User:${username}`,
fields: {
totalFollowers(prev) {
return prev + 1;
},
isFollowing(prev) {
return true;
}
}
});
}
const [followUser] = useMutation(FOLLOW_USER_MUTATION, {
variables: {
username,
},
onCompleted: followUserCompleted,
})