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

Apollo Client useFragment

Apollo Client useFragment

Yosuke Kurami

August 31, 2022
Tweet

More Decks by Yosuke Kurami

Other Decks in Programming

Transcript

  1. ͓඼ॻ͖ - ࣗݾ঺հ - @Quramy - GraphQL Tokyo ΦʔΨφΠβ -

    Web Frontend ΤϯδχΞ - ೔ࠒ͸ React (Next.js) / Apollo Client Ͱ͓࢓ࣄͯ͠·͢ - ࠓ೔࿩͢͜ͱ - Apollo Client ͷ Future ͬΆ͍ Feature ͷ࿩Λ͠·͢ - 2022.08.31 ࣌఺Ͱͷ৘ใͳͷͰɺࠓޙେ͖͘มߋ͞ΕΔՄೳੑ͕͋Γ·͢
  2. Collocation w/ AC 3.6 ਌$PNQPOFOU ࢠ$PNQPOFOU ਌2VFSZ ࢠ'SBHNFOU Colocated Component

    Colocated Component React Component Tree GraphQL Composition Tree useQuery Fragment Spread partial data as props
  3. Collocation via useFragment ਌$PNQPOFOU ࢠ$PNQPOFOU ਌2VFSZ ࢠ'SBHNFOU Colocated Component Colocated

    Component React Component Tree GraphQL Composition Tree useQuery Fragment Spread partial data as props Cache key useFragment
  4. useFragment ༗ແʹΑΔҧ͍ - ࠓ·Ͱ - ਌ Component ͕ Query ݁Ռͷ

    data Λ Apollo Cache ͔Βऔಘ͢Δ - Fragment ʹରԠ͢Δ data ͸਌ Component ͕ࢠ Component ΁ prop ͱͯ͠౉͢ - useFragment - ਌ Component ͕ Query ݁Ռͷ data Λ Apollo Cache ͔Βऔಘ͢Δ - ࢠ Component ͸ ਌ Component ͔Β Fragment ͷ Cache key ͷΈΛ΋Β͏ - Fragment ʹରԠ͢Δ data ͸ Component ࣗ਎͕ Apollo Cache ͔Βऔಘ͢Δ
  5. useFragment ͷಛੑ - ਌ -> ࢠ Component ͷ props όέπϦϨʔͰ͸ͳ͘ɺStore

    ૚͔ΒͷσʔλऔಘͱͳΓɺ ݸʑͷ Component ͕ΑΓࣗ཯తʹՔಇ͢Δ͜ͱʹͳΔ - React Redux ʹ͓͚Δ useSelector ʹ͍ۙଘࡏ - ແବͳมߋݕ஌Λճආ͠΍͍͢ - ਌ - ࢠ - ଙ ͱ͍͏ Component ֊૚ʹͳ͍ͬͯͨ৔߹ɺதؒ֊૚ͷมߋݕ஌Λͬ͢ඈ͹͠ ͯɺ຤અ͚ͩ࠶ Render Ͱ͖Δ $PNQPOFOU Store ( Apollo Cache ) useFragment $PNQPOFOU $PNQPOFOU
  6. Background Query - useBackgroundQuery = Apollo Client v3.8 ʹੵ·Ε͍ͯΔ৽ hook.

    ͜ͷ hook ͕ useFragment Λิ׬͢Δɺͱ͍͏ݐͯ෇͚ https://github.com/apollographql/apollo-client/pull/8783 - ػೳͷΠϝʔδʢଟ෼ʣ: - Redux ΍ pub/sub తͳΞφϩδʔͱͯ͠ཧղͰ͖ͳ͘΋ແ͍͕ɺࠓߋඞཁ͔ʁͱײͨ͡ HRMͷൃߦٴͼDBDIFߋ৽ useQuery = useBackgroundQuery + useFragment DBDIFσʔλͷߪಡ
  7. @defer / Suspense - v3.7 ʹ @defer, v3.9 Ͱ React

    Suspense ΁ͷରԠ͕༧ఆ͞Ε͍ͯΔ - @defer: Fragment ͷऔಘΛ஗Ԇͤ͞Δ GraphQL ͷ࣮ݧత࢓༷ - Suspense: Component Λඇಉظॲཧͱڠௐಈ࡞ͤ͞ΔͨΊͷ React v18ͷػೳ - @defer ͸ઌ೔ PR Խ͞Ε͍ͯΔ https://github.com/apollographql/apollo-client/pull/10018/files - ͨͩ͠ɺDeferred ͳ Fragment Λ Component ͔Βར༻͢Δͱ͍͏ έʔε͕·ͩߟྀ͞Ε͍ͯͳ͍໛༷
  8. @defer Directive - 1 Operation : ෳ਺ ResponseͱͳΔ - Fragment

    ʹ෇༩ - React ͷ Suspense for data fetch ͱ ਌࿨ੑߴ͍(͸ͣ) query ProductDetailQuery { product(id: 100) { id name imageURL ...DeferredPrice @defer } } fragment DeferredPrice on Product { specialPrice }
  9. @defer ͱ useFragment - GraphQL ͷΫΤϦ݁Ռͷ͏ͪɺҰ෦ͷ Fragment ͕஗Ԇ͞ΕΔ৔߹ɺ Fragment ຖʹҎԼ͕औಘͰ͖ͳͯ͘͸ͳΒͳ͍

    - ࠓ౸ୡͨ͠ͷ͔Ͳ͏͔ (= ඇಉظͷঢ়ଶ؅ཧ ) - ౸ୡ͍ͯ͠ΔͷͰ͋Ε͹ɺͦͷσʔλ - ͜Ε͸ݱߦͷ useQuery ͚ͩͰ͸೉͍͠͸ͣͰɺuseFragment ্͕هͷ ໾ׂΛ୲ͬͯ͘ΕΔ͜ͱΛظ଴͍ͯ͠Δ͕ɺઌ͸·ͩ௕ͦ͏ʁ
  10. ·ͱΊ - Apollo Client ͸ v4 ʹ޲͚ͯ৭ʑͳػೳ͕࣮૷͞Εͭͭ͋Δ - Relay ΍

    urql ͳͲͷ Client ϥΠϒϥϦͱൺֱ͢Δͱपճ஗Εؾຯ - طʹ Apollo Client Λӡ༻͍ͯ͠ΔͷͰ͋Ε͹ɺࠓͷ͏͔ͪΒ Fragment Colocation Λ΍͓͚ͬͯ͹ɺ useFragment ΁ͷஔ͖׵͑ࣗମ͸؆୯ʹ Ͱ͖Δ͸ͣ