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

Use GraphQL nicely 
with Nuxt.js

takanorip
February 26, 2018

Use GraphQL nicely 
with Nuxt.js

takanorip

February 26, 2018

Transcript

26 slides
  1. Self Introduction - Takanori Oki / @takanorip - SmartDrive inc.

    / Frontend Developer - React, Vue, Polymer, Web Creation - PolymerJapan Translation Team - I love free-font
  2. Reasons - Need flexible design for server-side - Many stakeholders,

    not fixed design, the specifications be fixed locally…å - Want to split the front-end and server-side tasks
  3. @nuxt/apollo-module - Nuxt.js module to use vue-apollo - vue-apollo is

    a library integrates Apollo in Vue components - Apollo is the GraphQL client for JavaScript - It was very difficult for me to upgrade to Apollo Client 2.0…
  4. import { ApolloLink } from 'apollo-link' import { HttpLink }

    from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' export default (ctx) => { const httpLink = new HttpLink({ uri: 'xxx' }) // middleware const middlewareLink = new ApolloLink((operation, forward) => { const token = 'xxx' operation.setContext({ headers: { authorization: `Bearer ${token}` } }) return forward(operation) }) const link = middlewareLink.concat(httpLink) return { link, cache: new InMemoryCache() } }
  5. query colors($id: Int) { colors(id: $id) { base_code base_name code

    images { car_color_id created_at image_url } name } }
  6. apollo: { cars: { prefetch: true, query: car, variables ()

    { return { id: this.id } }, fetchPolicy: 'cache-and-network' } }
  7. Using with asyncData - asyncData is called every time before

    loading the component - Apollo method is called after mounted, So users can see the blank page… - We need to call Apollo and get data before loading the component
  8. async asyncData ({ app, params }) { const result =

    await app.apolloProvider.defaultClient.query({ query: carInfo, variables: { 'id': parseInt(params.id, 10) } }) const cars = result.data.cars return { cars } }
  9. update - We can use a function for the query

    option and change data of the component - This will update the graphql query definition automatically
  10. apollo: { cars: { prefetch: true, query: carInfo, variables ()

    { console.log() return { id: this.id } }, update ({ cars }) { this.order.lease_plan_id = cars[0].plans[2].id return cars[0] }, fetchPolicy: 'cache-and-network' } }
  11. Feeling - It is useful for us because we can

    get variousɹ data from the same endpoint - When we need different data, we do only changing query - grahiql is very very useful !

More Decks by takanorip

Other Decks in Technology