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
120
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
370
Building Real-time Vue App
joere
4
4.7k
ReactNativeのAsyncStorageをNodeのReplから操作する
joere
0
350
Mock Native API in your E2E test
joere
2
1.2k
Other Decks in Technology
See All in Technology
MCP Appsを作ってみよう
iwamot
PRO
4
610
"何を作るか"を任される エンジニアは、どう育つのか
yutaokafuji
1
680
SONiCで構築・運用する生成AI向けパブリッククラウドネットワーク ~実装編~
sonic
0
200
FDE という解 ― 暗黙知と明示知をつなぐ、伴走型エンジニアリング ―
otanet
0
150
自宅LLMの話
jacopen
1
550
就職⽀援サービスにおけるキャリアアドバイザーのシフトスケジューリング
recruitengineers
PRO
1
140
AGENTS.mdとSkillsで始めるAIエージェント活用
sonoda_mj
3
210
How Timee Delivers Day 1 Production Ready LLM Features
tomoyks
0
220
Kiroで書いた 設計書 が AI レビューの 採点基準 になる
ezaki
0
110
EventBridge Connection
_kensh
5
710
フィジカル版Github Onshapeの紹介
shiba_8ro
0
210
AIっぽい文章を採点して人間らしく直すアプリを作ってみた
yama3133
2
150
Featured
See All Featured
Ethics towards AI in product and experience design
skipperchong
2
310
Bash Introduction
62gerente
615
220k
How to Grow Your eCommerce with AI & Automation
katarinadahlin
PRO
1
210
New Earth Scene 8
popppiees
3
2.3k
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
11k
Marketing to machines
jonoalderson
1
5.4k
svc-hook: hooking system calls on ARM64 by binary rewriting
retrage
2
300
A Tale of Four Properties
chriscoyier
163
24k
Raft: Consensus for Rubyists
vanstee
141
7.5k
How STYLIGHT went responsive
nonsquared
100
6.2k
Visualization
eitanlees
152
17k
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
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!