Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data feching and caching on Apollo Client

joe_re
September 15, 2017

Data feching and caching on Apollo Client

2017/09/15 ToKyoto.js LT

joe_re

September 15, 2017
Tweet

More Decks by joe_re

Other Decks in Technology

Transcript

  1. What is Apollo Client? GraphQL のClient ライブラリ React 、Angular 、Vue

    、NativeApp(ReactNative, iOS, Android) などなど幅広くサポート 対抗馬はFacebook 製のRelay
  2. 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 } } } }
  3. 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 }
  4. Example of Subscription subscription sub { newMessage { ... newMessageFields

    } } fragment newMessageFields on Message { body sender }
  5. 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> ) } }
  6. Creating a client and inject via a provider 作成したclient はprovider

    を通じて各コンポーネントで 利用可能となる graphql() を用いてGraohQL Container を作成することが できる GraphQL Container は与えるprops の変化によるfetch を 自動で行う client を直接呼び出して使用することも可能( withApollo())
  7. 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);
  8. 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 }; } }) } } } }));
  9. 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);
  10. Automatic store updates 例ではMutation の発行のロジックしか書いていないにも関わ らず、store のデータも更新される mutation の結果で返ってきているid と同一のものがstore

    にあ る場合には、store も同時に更新される mutation RemoveStar($input: RemoveStarInput!) { removeStar(input: $input) { starrable { id stargazers { totalCount } viewerHasStarred } } }
  11. if you can't use automatic store updates... mutation のオプションを通じて手動でstore をupdate

    するこ とが可能 refetchQueries: mutation の後に再度query を発行しデータを 更新する update: mutation の後にstore のcache を直接いじってデータ を更新する updateQueries: deprecated
  12. あえて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);