Welcome to apollo graphql + react query

Posted on

1/3/2023

Cover Image for Welcome to apollo graphql + react query

Best api tool i’have ever used.

ไม่ต้องทำ global storage / state management อีกต่อไป

เกิดอะไรขึ้นในปี 2022!!

pain ในปีเก่าๆ

  1. เวลายิง request แล้วต้องเก็บ response ไว้ที่ไหน ถ้าจะใช้หลายๆที่
  2. เวลามี state ที่จะใช้ร่วมกันหลายหน้ามากๆต้องทำยังไง
  3. เขียน global state management เป็น pain มากๆ learning curve สูงปริ้ด mobx, redux คืออะไร
    1. redux saga, redux thunk, mobx 4, mobx 5
  4. เรา handle state loading ของแต่ละ request โดยการเอามันไปแปะไว้ใน global state เพราะว่าต้องใช้ global state ในการยิง api
Future

welcome to the future

React ได้ออก version 16.8 ที่คิดว่าเป็น major change มากที่สุด ( 2018 )

  • เอา useState เข้ามา
  • มี useContext

ตอนนี้ community ก็บอกกันว่า เห้ย useContext มันจัดการได้เหมือน redux เลยวะ แล้วเราจะใช้ redux กันทำไมวะ
ตอนนั้น technology ยังไม่ได้ imprement useContext กัน

แต่ว่าตอนนี้ หลายๆ lib มี useContext เรียบร้อยแล้ว และ 1 ใน key lib ที่ทำให้ชีวิตง่ายขึ้นก็คือ react query

React Query

Fetch, cache and update data in your React and React Native applications all without touching any "global state".

ใช่ครับ เราสามารถจัดการ request state ได้ โดยที่ไม่ต้องใช้ global state

เพราะว่า React Query ได้ Cache Request – Response ไว้แล้วใน Context and Provider ของ React ทำให้ถ้าเรายิง request นั้นซ้ำไปเรื่อยๆ Request นั้นจะไม่ถูกส่งออกไปที่ backend แต่มันจะใช้ cache แทน

But Why apollo graphql

จริงๆแล้ว React Query ก็สามารถใช้กับ REST-Api ได้นะครับ

Example

useProfileQuery = useQuery("profileKey", async () => api.getProfile())

ทุกครั้งที่เรียก profileKey มันก็จะใช้ response นี้กลับมาตลอดเหมือนกันครับ

แต่ว่า ถ้าอย่างนั้นทุก function ที่เราไป call มันก็จะมี key ตลอดเวลาเลยหน่ะสิ มันก็ยุ่งยากเหมือนเดิมแหะ

Apollo

อย่างแรกเลย Apollo สามารถ custom query ได้แบบ vary มากๆ และไม่ต้อง concern เรื่อง error handling กับการที่ client ลืมไปแล้วว่าต้องยิง endpoint ไหน

concept ของ graphql มีแค่สองอย่าง

query and mutation

อย่างที่สอง Apollo-GraphQL มี plugin ตัวนึงที่ทำให้เราสามารถ integrate กับ react-query ได้แบบง่ายๆ

เรียกว่า graphql-codegen

ปกติแล้ว เวลาเราเขียน query graphql version เก่าๆ เราก็จะต้องเขียนแบบ

POST /someendpoint/graphql `query getProfile { id username }`

แต่ถ้าเราใช้ codegen แล้วมันจะ gen type + action มาให้เราเสร็จสับเช่น1useGetProfile() ก็จะได้ response เดียวกับข้างบน

ถ้าเราใช้ codegen แต่ไม่ได้ใช้ plugin react-query ก็จะเขียนประมานว่า

useQuery("profileKey", () => useGetProfile())

แต่พอเรา implement react-query เข้าไป เราก็แทบจะไม่ต้องทำอะไรเลยและเราจะเรียกใช้กี่ครั้งก็ได้ ในการเปิดเวป 1 ครั้ง ก็จะได้ result เดิม แบบ cache ไว้ ไม่ต้องเก็บเองให้เสียเวลา

const { data, error, isLoading } = useGetProfile()

ตัวแปรพวกนี้ react-query จัดการให้หมดเลย เราจะใช้ตรงนี้ใน level ไหนก็ได้

เช่น level component ก็ได้, level custom hook ก็ได้

Apollo
React
ReactQuery
avatar-image

By Thitiwat Thongbor

Written on:

1/3/2023

More Stories