ทำ Custom hooks ใช้งานร่วมกับ onSnapshot (Cloud Firestore)

Moo Thanathorn
Mintelligence
Published in
Nov 28, 2019

เนื่องจากในโปรเจคที่ผมมีส่วนร่วม มีการใช้งาน React กับ Cloud firestore และต้องการแสดงผลแบบ Realtime นั้นต้องอาศัยฟังก์ชัน onSnapshot() ในการรับข้อมูลแบบทันที

credit : https://firebase.google.com/docs/firestore/query-data/listen?authuser=1

ตัว onSnapshot นั้นสามารถบอกลักษณะของ Change ที่เกิดขึ้นได้ว่าเป็นการเปลี่ยนแปลงข้อมูลชนิดใด

credit : https://firebase.google.com/docs/firestore/query-data/listen?authuser=1#view_changes_between_snapshots

การนำมาใช้ร่วมกับ React Hooks จะต้องทำเป็น Custom hooks ขึ้นมาโดยใช้ useState เป็นตัวไว้คอยเก็บค่า isLoading ไว้ใช้กับ loader , data ใช้เก็บข้อมูลที่มากจาก firestore และ error ส่วน useEffect นำมาใช้คล้ายๆกับ lifecycle hook componentDidmount() เมื่อเรียกใช้ onSnapshot จะเป็นการ subscribe รอการ callback อยู่ตลอดเวลา

เมื่อเราอยากจะ unsubscribe ก็สามารถทำได้โดย สร้างตัวแปร unsub มาเก็บฟังก์ชัน onSnapshot ของเราตรงบรรทัดที่ 15 จากนั้น ไปเรียกใช้ใน clean up ฟังก์ชันของ useEffect

*** ผมลองใช้วิธีนี้แต่ไม่ทราบเหมือนกันว่าทำไมมันไม่ unsubscribe ให้ ถ้าเพื่อนๆมีวิธีที่ดีกว่าแนะนำกันมาได้นะครับ

สามารถอ่านเพิ่มเติ่มได้ที่ : https://medium.com/firebasethailand/%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%A1%E0%B8%82%E0%B9%89%E0%B8%99%E0%B8%81%E0%B8%B1%E0%B8%9A-firebase-cloud-firestore-%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A%E0%B8%90%E0%B8%B2%E0%B8%99%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%83%E0%B8%AB%E0%B8%A1%E0%B9%88%E0%B8%A5%E0%B9%88%E0%B8%B2%E0%B8%AA%E0%B8%B8%E0%B8%94%E0%B8%88%E0%B8%B2%E0%B8%81-firebase-%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B9%80%E0%B8%95%E0%B9%87%E0%B8%A1-d001e43e2be7

https://reactjs.org/docs/hooks-effect.html

--

--