apollo ๊ณต์ ๋ฌธ์๋ฅผ ๋ฒ์ญํ์์ต๋๋ค.
readQuery
writeQuery
๋ฅผ ์จ๋ผ.const READ_TODO = gql`
query ReadTodo($id: ID!) {
todo(id: $id) {
id
text
completed
}
}
`;
// Fetch the cached to-do item with ID 5
const { todo } = client.readQuery({
query: READ_TODO,
variables: { // Provide any required variables here
id: 5,
},
});
writeQuery
readQuery
์ ๊ฑฐ์ ํก์ฌํ์ง๋ง, data
option์ด ์๋ค๋ ๊ฒ ๋ค๋ฅด๋ค.client.writeQuery({
query: gql`
query WriteTodo($id: Int!) {
todo(id: $id) {
id
text
completed
}
}`,
data: { // Contains the data to write
todo: {
__typename: 'Todo',
id: 5,
text: 'Buy grapes ๐',
completed: false
},
},
variables: {
id: 5
}
});
graphQL queris
์ ๋ค๋ฅด๊ฒ id
option์ ์๊ตฌํ๋ค.readFragment
Copy
const todo = client.readFragment({
id: 'Todo:5', // The value of the to-do item's cache ID
fragment: gql`
fragment MyTodo on Todo {
id
text
completed
}
`,
});
writeFragment
client.writeFragment({
id: 'Todo:5',
fragment: gql`
fragment MyTodo on Todo {
completed
}
`,
data: {
completed: true,
},
});
writeQuery
๋ writeFragment
์ฒ๋ผ modify
๋ subscription๋ค์ trigger ํ ์ ์๋ค.broadcast:false
๋ฅผ ์ ๋ถ์ธ๋ค๋ฉด..cache.identify
๋ฅผ ์ธ ๊ฒ์ ์ถ์ฒ.cache.modify({
id: cache.identify(myObject),
fields: {
/*name ํ๋์ ๊ฐ์ ๋ชจ๋ ๋๋ฌธ์๋ก ๋ฐ๊พธ๋ ์ฝ๋*/
name(cachedName) {
return cachedName.toUpperCase();
},
},
/* broadcast: false // Include this to prevent automatic query refresh */
});
// readField๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
const idToRemove = 'abc123';
cache.modify({
id: cache.identify(myPost),
fields: {
comments(existingCommentRefs, { readField }) {
return existingCommentRefs.filter(
commentRef => idToRemove !== readField('id', commentRef)
);
},
},
});
const newComment = {
__typename: 'Comment',
id: 'abc123',
text: 'Great blog post!',
};
cache.modify({
id: cache.identify(myPost),
fields: {
comments(existingCommentRefs = [], { readField }) {
const newCommentRef = cache.writeFragment({
data: newComment,
fragment: gql`
fragment NewComment on Comment {
id
text
}
`
});
// Quick safety check - if the new comment is already
// present in the cache, we don't need to add it again.
if (existingCommentRefs.some(
ref => readField('id', ref) === newComment.id
)) {
return existingCommentRefs;
}
return [...existingCommentRefs, newCommentRef];
}
}
});
// useMutation ํ ๋ cache ์ด๋ป๊ฒ ์
๋ฐ์ดํธ ํ๋์ง!!
const [addComment] = useMutation(ADD_COMMENT, {
update(cache, { data: { addComment } }) {
cache.modify({
id: cache.identify(myPost),
fields: {
comments(existingCommentRefs = [], { readField }) {
const newCommentRef = cache.writeFragment({
data: addComment,
fragment: gql`
fragment NewComment on Comment {
id
text
}
`
});
return [...existingCommentRefs, newCommentRef];
}
}
});
}
});
cache.modify({
id: cache.identify(myPost),
fields: {
comments(existingCommentRefs, { DELETE }) {
return DELETE;
},
},
});
cache.modify({
id: cache.identify(myPost),
fields: {
comments(existingCommentRefs, { INVALIDATE }) {
return INVALIDATE;
},
},
});