Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Data feching and caching on Apollo Client
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
joe_re
September 15, 2017
Technology
3k
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Data feching and caching on Apollo Client
2017/09/15 ToKyoto.js LT
joe_re
September 15, 2017
More Decks by joe_re
See All by joe_re
Eyes on Claude Code
joere
0
130
Building Public API with GraphQL
joere
3
140
Traversing the GraphQL AST and Calculating Query Costs
joere
0
1.3k
Real-Time applications with GraphQL
joere
0
300
Prisma2 with Graphql
joere
3
1k
Go beyound static on Netlify
joere
1
380
Building Real-time Vue App
joere
4
4.7k
ReactNativeのAsyncStorageをNodeのReplから操作する
joere
0
360
Mock Native API in your E2E test
joere
2
1.2k
Other Decks in Technology
See All in Technology
フルAIで個人開発して学んだあれこれ / yuruai vol.1
isaoshimizu
0
120
AIのReact習熟度を測る
uhyo
2
680
【Snowflake Summit 2026 Recap!!】Snowflake Summit Deep Dive: Security & Governance
civitaspo
1
310
GitHub Copilot app最速の発信の裏側
tomokusaba
1
260
GitHub Copilot 最新アップデート – 「一歩先」の実践活用術
moulongzhang
5
1.7k
作る力から、見極める力へ — AI時代に広がるエンジニアの価値と役割
rince
0
330
「ビジネスがわかるエンジニア」とは何か?
ryooob
0
300
AWS Security Hub CSPMの成功・失敗体験
cmusudakeisuke
0
540
MUSUBI 田中裕一『AIと共に行う「しごとのリデザイン」- スモールバックオフィス編』AI Ops Lab #4
musubi
0
310
When Platform Engineering Meets GenAI
sucitw
0
170
AIチャットの改善から見えた、良いAI体験とは / What Constitutes a Good AI Experience: Insights from Improving AI Chat
kubode
0
120
AIをフル活用してオンコール機能のプロトタイプを2日で作った話 / Building an AI-Powered On-Call Prototype in Just Two Days
nari_ex
0
130
Featured
See All Featured
[SF Ruby Conf 2025] Rails X
palkan
2
1.1k
Fashionably flexible responsive web design (full day workshop)
malarkey
408
66k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
123
22k
Ten Tips & Tricks for a 🌱 transition
stuffmc
0
140
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
170
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
Done Done
chrislema
186
16k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
231
55k
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
Game over? The fight for quality and originality in the time of robots
wayneb77
1
200
Paper Plane
katiecoart
PRO
1
52k
KATA
mclloyd
PRO
35
15k
Transcript
Data feching and caching on Apollo Client 2017/09/15 ToKyoto.js LT
@joe_re
Who am I? twitter: @joe_re github: @joere working in freee.K.K
GraphQL Tokyo Organizer
What is Apollo Client? GraphQL のClient ライブラリ React 、Angular 、Vue
、NativeApp(ReactNative, iOS, Android) などなど幅広くサポート 対抗馬はFacebook 製のRelay
vs Relay
の話はしないけどざっくりApollo が優位なところをざっくり サポートはReact, ReactNative のみ GraphQL API に制約をかける 規約が多いので理解するまで大変 (
ただし慣れればパフォーマンスやDE は向上する)
Fundations of GraphQL
What is GraphQL Facebook が公開しているAPI の仕様 データの取得、更新を行うクエリ言語を提供する 特定の言語やフレームワークを指すものではない
Example Query query { repository(owner: "apollographql", name: "apollo-client") { name,
description, stargazers { totalCount } } } Result { "data": { "repository": { "name": "apollo-client", "description": ":rocket: A fully-featured, production ready caching GraphQL client for every server or UI framework", "stargazers": { "totalCount": 3948 } } } }
Good Points クライアント側で必要なデータを細かく取捨選択できるの で無駄がない 複数のリソースを1 つのリクエストで一度に得られる クライアントが理解できるスキーマを元にクエリするの で、期待した結果を得られる( 型定義も容易) (http://graphql.org/)
Three types of GraphQL operation Query: データの取得 Mutation: Query で取得したデータの更新
Subscription: データの変更の購読(Response Stream)
Example of Query query SearchRepository($queryString: String!, $cursor: String) { search(query:
$queryString, type: REPOSITORY, first: 30, after: $cursor) { repositoryCount edges { cursor node { ... RepositorySearchResult } } } } fragment RepositorySearchResult on Repository { databaseId name owner { avatarUrl(size: 40) login } description stargazers { totalCount } forks { totalCount } updatedAt }
Example of Mutation mutation AddStar($input: AddStarInput!) { addStar(input: $input) {
starrable { viewerHasStarred } } }
Example of Subscription subscription sub { newMessage { ... newMessageFields
} } fragment newMessageFields on Message { body sender }
※ ここからようやくApollo Client の話
DEMO (GitHub Client)
実装例にはReact を使います
Creating a client and inject via a provider const networkInterface
= createNetworkInterface({ uri: 'https://api.github.com/graphql' }); const middleWareInterface: MiddlewareInterface[] = [{ applyMiddleware(req, next) { const headers = req.options.headers || {}; AsyncStorage.getItem('token').then((token) => { headers.authorization = token ? `Bearer ${token}` : ''; req.options.headers = headers; next(); }); } }]; networkInterface.use(middleWareInterface); const client = new ApolloClient({ networkInterface }); export default class App extends React.Component { render() { return ( <ApolloProvider client={client}> <Routes /> </ApolloProvider> ) } }
Creating a client and inject via a provider 作成したclient はprovider
を通じて各コンポーネントで 利用可能となる graphql() を用いてGraohQL Container を作成することが できる GraphQL Container は与えるprops の変化によるfetch を 自動で行う client を直接呼び出して使用することも可能( withApollo())
Creating a GraphQL Container function ReleasesPage(props: Props & AppoloProps) {
if (props.loading) { return <Text>Loading</Text>; } return ( <View style={styles.page}> <ReleaseList repository={props.repository} navigation={props.navigation}/> </View> ); } const withData: OperationComponent<ShowReleasesQuery & QueryProps, Props, Props & AppoloProps> = graphql(RELEASES_QUERY, ({ options: ({ owner, name }) => ( { variables: { owner, name }, notifyOnNetworkStatusChange: true } ), props: (props) => { const { loading, repository } = props.data; return { loading, repository, } } })); export default withData(ReleasesPage);
GraphQL では大抵のリソースが 1 つのリクエストで取れる
件数が膨大なデータに対しても 1 つのリクエストで取得できる??
そんなわけはない
件数が多ければ当然 その分レスポンスは遅くなる
つまりページネーション が必要
data.fetchMore ページネーションを実現するためのAPI 現在のfetching の状態をcache に残したまま、新しく取得し た結果をマージすることができる Relay.QL のcursor のパターンだけではなく、どのページネ ーションのパターンにでも使える
Example of Pagination const withData: OperationComponent<SearchRepositoryQuery & QueryProps, Props, Props
& AppoloProps> = graphql(REPOSITORY_QUERY, ({ options: ({ queryString }) => ( { variables: { queryString }, notifyOnNetworkStatusChange: true } ), props: (props) => { const { loading, search, fetchMore } = props.data; return { loading, searchResult: { search }, loadNextPage: (cursor) => { return fetchMore({ variables: { cursor }, updateQuery: (prev, data) => { const { search } = data.fetchMoreResult; search.edges = prev.search.edges.concat(search.edges); return { search }; } }) } } } }));
Updating fetched data データの更新には前述の通りMutation を使う Mutation もQuery と同じように graphql() を用いて使用可能
になる Mutaion の場合はQuery とは違い、props の変化に応じて実行 されない
Example of Mutaion function StarBadge(props: Props) { return ( <Badge
containerStyle={{ width: 160, height: 30, backgroundColor: '#fff', marginRight: 8 }} onPress={() => rops.repository.viewerHasStarred ? props.removeStar(repository.id) : props.addStar(repository.id)}> <Text>{//... 省略}</Text> </Badge> ); } const StarBadgeWithMutations = compose( graphql(ADD_STAR_MUTATION, { props: ({ ownProps, mutate }) => ({ addStar: (id: string) => mutate({ variables: { input: { starrableId: id } }, }) }) }), graphql(REMOVE_STAR_MUTATION, { props: ({ ownProps, mutate }) => ({ removeStar: (id: string) => mutate({ variables: { input: { starrableId: id } }, }) }) }) )(StarBadge);
Automatic store updates 例ではMutation の発行のロジックしか書いていないにも関わ らず、store のデータも更新される mutation の結果で返ってきているid と同一のものがstore
にあ る場合には、store も同時に更新される mutation RemoveStar($input: RemoveStarInput!) { removeStar(input: $input) { starrable { id stargazers { totalCount } viewerHasStarred } } }
if you can't use automatic store updates... mutation のオプションを通じて手動でstore をupdate
するこ とが可能 refetchQueries: mutation の後に再度query を発行しデータを 更新する update: mutation の後にstore のcache を直接いじってデータ を更新する updateQueries: deprecated
あえてupdate を使ってcache を更新してみた const StarBadgeWithMutations = compose( graphql(ADD_STAR_MUTATION, { props:
({ ownProps, mutate }) => ({ addStar: (id: string) => mutate({ variables: { input: { starrableId: id } }, }) }) }), graphql(REMOVE_STAR_MUTATION, { props: ({ ownProps, mutate }) => { return { removeStar(id: string) { mutate({ variables: { input: { starrableId: id } }, update: (store, { data }) => { const queryOption = { query: RELEASES_QUERY, variables: { owner: ownProps.repository.owner.login, name: ownProps.repository.name } }; const cache = store.readQuery(queryOption); cache.repository.viewerHasStarred = data.removeStar.starrable.viewerHasStarred; cache.repository.stargazers.totalCount -= 1; store.writeQuery(Object.assign({}, queryOption, { data: cache })); } }) } } } }) )(StarBadge);
大変なのでなるべく Automatic store updates しましょう!
https://www.meetup.com/jaJP/GraphQLTokyo/ (多分)来月meetup するので、ご興味があればぜひ!
Thank you for your attention!