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
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
310
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
NDIAS CTF 2026 問題解説会資料
bata_24
0
180
テスト設計の本質を改めて考えてみる~生成AIを活用する時代だからこそ、作ったテストの説明性を高めよう~
yamasaki696
1
400
小さいから、全部わかる。— 常駐AI "xangi" のすすめ
sugupoko
0
280
しぶいSRE: サーバから見えない障害にどう向き合うか。ラストワンマイルのデバッグ実践 / Shibui SRE
kanny
12
5.3k
cccccc
moznion
0
1.8k
最適な自走を最小限の支援で — M&Aで拡大する組織で少人数SREが挑んだ1年 / SRE NEXT 2026
genda
0
510
Road to SRE NEXTの今までとこれから
hiroyaonoe
0
230
Control Planeで育てるBtoB SaaSの認証基盤 - SRE NEXT 2026
pokohide
1
1.8k
Claude Codeとハーネスについて考えてみる
oikon48
18
8.8k
記録をかんたんに、提案をパーソナルに ── AIであすけんが目指すもの
oprstchn
0
170
Zoom2Youtube.Claude
kawaguti
PRO
3
470
ポストモーテム! DDoSからサイトは守れた。 でもビジネスは守れなかった。
bengo4com
0
2k
Featured
See All Featured
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
67
56k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
Tips & Tricks on How to Get Your First Job In Tech
honzajavorek
1
560
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
350
sira's awesome portfolio website redesign presentation
elsirapls
0
300
[RailsConf 2023] Rails as a piece of cake
palkan
59
6.7k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
320
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Leveraging LLMs for student feedback in introductory data science courses - posit::conf(2025)
minecr
1
310
The B2B funnel & how to create a winning content strategy
katarinadahlin
PRO
1
420
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
Building the Perfect Custom Keyboard
takai
2
810
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!