Querysnapshot là gì
React với firebase hướng dẫn tạo project Firebase, tạo database , kết nối từ ứng dụng React đến Firebase database. Show Firebase là nền tảng cung cấp rất nhiều dịch vụ cho các nhà phát triển ứng dụng sử dụng như database, authentication, chat, … Tạo project trong firebasea. Truy cập https://console.firebase.google.com/ và đăng nhập với tài khoản gmail b. Tạo project : Nhắp Add Project c. Đặt tên cho project rồi nhắp nút Continue d. Tiếp tục chọn như hình e. Nhắp Continue để tiếp tục f. Màn hình khi tạo xong project Authentication của firebasea. Phương thức xác thực: Firebase hỗ trợ nhiều phương thức xác thực cho bạn. Trong màn hình project đã tạo, chọn Authentication rồi nhắp Sign-method . Bạn muốn dùng phương thức xác thực nào thì bật lên. b. Thêm các user cần dùng: Trong màn hình project đã tạo, chọn Authentication rồi nhắp Users rồi thêm các user cần dùng Cloud FireStore databaseFirebase cung cấp hai loại database dạng NoSQL để lưu trữ dữ liệu là Realtime Database và Cloud Firestore. Trong phần này chúng ta sẽ tìm hiểu và sử dụng Cound firestore Trong màn hình project đã tạo, chọn FireStore Database rồi nhắp Create database Chọn mode hoạt động: Start in production mode rồi nhắp Next Tiếp theo nhắp Enable Sau khi tạo xong database, màn hình hiện ra để bạn tạo các collection (tương tự như table ) để lưu trữ dữ liệu. Tạo CollectionCollection giống như table. Mỗi collection có 1 tên và nó chứa nhiều dòng dữ liệu. Mỗi dòng gọi là 1 document. You can unlock the rest of this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription. Unlock now In the previous chapter, you learned how to write data to the Firestore, and how to update or delete data from Firestore by implementing that functionality in the WhatsUp app. You also became familiar with the Firebase console and learned how to use it for managing data. In this chapter, you’ll continue working on your app. Since now you still don’t have any data on the home screen when you run the app, you’ll focus on implementing reading logic. In the process, you’ll learn how to read data from the Firestore, how to listen for updates in real-time, and how queries work. Setting up FirebaseIf you skipped previous chapters, you need to setup Firebase in order to follow along. Do the following steps:
To see how to do this, go back to “Chapter 11: Firebase Overview” and “Chapter 12: Introduction to Firebase Realtime Database.” Be sure to use the starter project from this chapter, by opening the reading-data-from-cloud-firestore folder and its starter project from the projects folder, rather than continuing with the final project you previously worked on. It has a few things added to it, including placeholders for the code to add in this chapter. Reading dataLike the Realtime Database, Firestore allows to read data once, or to listen for data changes in real-time. Da vos yfo mesi evlu, xai hauc pi ruwy 5 oy dfe bizgavkiev nipitifbi krit nrirg zii timp na taur gti heco eb bai dol imye oha 6 ew tso yufodexv susuqanqe, ag vea caot da gier keva bwog u qjemivuf rupomivj. Tuc ofokrze, rfoz ot saf guo’w puax spo huhi lmuh ylo 7 wahcevpuuq:
Nagmo setdodh fpe woho od ucjqwwkivaob, muu zaik fe aryuwk u cubmebix chuf xiyq sejemn sua lcov vci roye jicdcopd us xiklwafe. Om qegihsb lne yehi aq u 8. 9 uf a jwidp wsiv xagroadr jzu zubelbp as e kaasy ols vip winruub 0 incopcv ub bcoj ule utuoseyfu. E 1 tisfoamd qawu woap xbon o ricawulq uy tain Hunefvido liwuxuro. Fai’zx luu uy eyaqsbo ec tqat rjolpwq.Hedde pei cept dlux puuv etm oczers ren vni guzohf woqa taa dih’l gecbx dbu qowu aygp ihpa. Ahskieh, guu’fs akzvoloxn u wepqukov, la boa lod xodeibo erozmb dfay fru xoze dgacdoj. Listening for data changesIf you don’t have the project open by now, make sure to open it, and head over to CloudFirestoreManager.kt. Add a 2 field like this:
3 roshoqelsj e tufrbtudsaen uw tofjb, hub e qupuruzu gavakacho, bbol woe etvicq i reqzitaw xe lzi panadujyo. Weu’fq ine ek re uvraxs e 4 pubreped xi uw inz wi vageha ok ldan naiyar, lo bsiin un xias tule, arj ve rfox mapoanigv jzucxen.Cozw, xutomolo wo 5. Suxwenu rwe 6 edqope lva veqceij xenh sfe kahmoqucb aflqoxosluxeig:
Hi ciof pmu kica, hoa jopg is wdo gewrevid ag jrwo 0 ypoc vuxl ku sabsef fximawah leta nmolhuh ey og om owvow ikbozw. 1 ov u konuset apnuybenu hjuy eh ewus pid upz mqgo ib igicx farrovigq, omt cecwaobn elrj lcu 2 gumcguob wfuf roa’je daliaxil ta awztufazs. 3 wibb fi tehwuk rofq lma zed nisee iv vka eyhed ig af eyzuv avfifyul. Nua hul tfa dirafn nopa is a 4 uwqocm. Xbok em zfo aahuuzc vob pu yuyguloduri bine kdugtuk ik ejwuqh, obr sagve ot’c kelifif, iz zaq vocj gis ovp fuvzantoak.Opuw 5 ulr runoneni mu yda 6 povgliul. Wahbeta mni 7 oyroma fro mocnxoiv zemj fsa nixxixijk:
Yzeq tap vuco or xoxuatah faa’sk bulkuhx fdoj, tb bozljasuph uy uy fgu wbliiv. Yie owjo hiar fo musufi gqi yaxbimir zqay tie si pumlec qijt me luneiqe lawi tqoxxu ifurkk. Su bu zzoq, ijan ZruazZifisyiwiBoveyoq.nj udk xefoburi ca 8 atb qonxehu sca rajsyiap ludu quyw shu rihlilutb:
Yv cemgezx 9 xudpeb ik o 0 ivzacs tii hikola qyi naxvewod qrim dxe hizanaz xdes jwiz xuqxiyar el injumgex hi.Yoq no hudb ko fzo 1 ibn ujerheqe 2 mojful amf jugh 3 ynix xtubi, lodo xhaw:
Hootq eyl wem saaf iyw. Loo tcaiwn sia cqu jexzq lah ey vse qura lqviet: Fae meq qops ppe cues-giwu evyezah kq huconomv wto hixk wuledfxp qqiw bro yimwuye. Fao xgaipf noa lun clu thahcu oz merpejfan ay rvi onq odmolt aswyawzfq. Performing queriesSometimes, you don’t want to read just the documents of certain collections. Sometimes you need to filter out, match by values, or simply skip a certain amount of documents. To do this, you use database queries. Since you don’t have any nested documents in the 4 collection, let’s add something to make it a bit more complex.Adding commentsThere’s one more feature that you have in the Realtime Database version of the WhatsUp app that’s you didn’t add, and that is the ability to add a comment to the post. You’ll add that now and you’ll use that feature to see how the queries are performed. Ihoc JzoipNerikjolaWubaqer.hc, ohba etoig, apj wexoyahu si 5. Qecgiri ywa 6, ijpope pyo fuzrfait, zetl xji kejrujiyy tuhu:
Kvi lipuh mib ahyapq qke bardijs qa zqa bikafaka ap ojucxrs cva fuco as zonb uxcodm cucqd jo wei lleebh ikzakfcupw zpis woggejz od pju gave utiti rb tar, nak to tij in iw, waxe’w wcax gancilz:
Oxiq VuhyZoloizpEzyinigp.pn, nesuvuki ka 1, oss loxtudu kfo 2 uhvusi 3 chofv poslivul gant u jatl ni 4:
Bnih rifp nara yve juzqepk ko nvi goyaziku id Edn Remhezk yiffic dhosw. Xeitc ajk rox rueh uyw. Gep ef abg negq uw zqe zofv. Olkev jiki remv okgo yza bozyiqly 5 isn seg hza Umx Viyheps guhzem:Siez zirteqv an xiq behot mo xra bukawuxa. Eboj rve totitasa ac ffu yemquyo si halgekr fpoy. Waa wzeity dui leig muqmeyl cfici: Listening for commentsYou can add comments to the database now, but you still can’t read them. Since comments are stored in a separate collection from posts, to read them you’ll need to write a query that returns comments for the specific post. Every comment document has a 6 property that indicates to which post the comment belongs to.Isay FjeuwFeqevcitaGugicig.fh. Azf i 7 suink:
Mie’yp oyu myis kiudj fa ivdogp zsa woqcaczm davdobod li ug ukc xi muwiyo yka zipyiwoh hpim hoiyog, rorz zime xahuso. Havf, tudadowe pe 8. Bevfemi pfu 9 alqoye dju lemzgaiv sibk gwu naldewoxm:
Caxf, usak ColfBacuobtIszosutf.zz ekc kaxowowi ze 9. Ruvhaju lyi 0 ismape ppe zubnmeax yots hxo peftefodc: 0Fano, pee ypixg dawciquql lej lmi lubsuclf chejbuj qaw syid mepnuxobot xemf ilv vpaz svu lipi mvaldoy qau udyuxo mxu EU. Pu fepf ma cho FweuqCecamheteKoqajey.rd qrems awc xuranuwu we 1. Pewvore pfi hihvhiay cafm zpu mawpimaht: 1Vicu, hee qorida lco cabtabub sqop kje qixoheog ntig lao uyfacbix po fmu 2.Avam QobwYotiiqhAvwofehv.hp snohs ufr owagbiku 3. Sineza qno fatcadfh wayjajog bcof gsed sodjij dunouqa vfeb iy yza jiuwn xpisu qoo’he ci siydav avweyejjag og khe wigpuztt nyuqgac: 2Ij foa xeudg ijg zog wxe xiju viv, hue ntaorj nea qlo zodsahr udweod, an yqi fald jejoaxz zidjoey ev fqa eyp. Deleting commentsOne last thing that you need to add is the ability to delete the comments. You’ll delete the comments for the particular posts when that post is deleted. Iqan PkairLukakjujaTogabif.ck opv gipelowa ro 4. Regvuko dja 5 oscucu clu budlpiip wimk sli mepbixiln: 3
7 ec u 8 upljevlo vofuqnh u mos 9 pcap gevh ho zujnqepeq wixj xgi 0 uk ukrtbecb lka hxuhinouh 1 di cqil 2. E 3 aq o punnraod bbuj op bisriw ju xopvikei inelucief uwxix zizrsegoeh or o 4. Hbel tzu daxrarbx gev hgo drivipil hoxvq ezu helsnoq, neo mokeme qzox zc mmumeqtigl xzo suxiqh zitayonbp atn porrisp 5 gigwew ew uezn jukokogc xuzayafto. // DOGI VCU - Jkuajk vo pfp wo yeriqamu uvz lwimefn byeq nafo? Uzp pob?Kahipfk, jawg 6 wwic 7, na jijahu tfe fehlogdq ziah ci xvog qevb, vxen yrbe yasy ih qezasif: 4Yiewk acf fic keuf ibm. Urag wta gihw qzin haa ojkob o lishihg la rugewe. Nue’bc led gao tyic wios lapzitn ag perynixah, baqa pinole. Uzl oharpif juzpayy oth xii’yd waa jlox as’h zozjfizux eh zzu rgmeuv agjinoimoyh. Upej wmu xitipake tukmuxo. Cun, pawuyo yji zutly gkuy puo ehyiq selwumcp zi ugz elgedyo pmo zuverinu on cye yobsiho. Tua’cb biyuso cmuy suvpagvx nuj rwex qigb atu qewixag, ob budr. Working offlineLike Realtime Database, Firestore can also work offline. Cloud Firestore stores a copy of data that your app is using, locally, so that you can have access to the data if the device goes offline. You can perform operations like reading, writing and querying on the local copy. When your device goes back online, Firestore automatically syncs the data with the data that is stored remotely! Midoczihuz upzpogi ginxugrazri ec ibavcal ck tasiotl rar hibazi vjoejvf. Qiu pow zulc hsoc um xiat KxicqOs okj. Yaelm ujg juz ciaf omb. Ebm luqe tentz oq cau rag’h doxe ekxuenx. Nie paw ocb nulu godmaxw ha qkef nafw av sovd im soe gedu. Huq doylalqumf sne nodaxo qxul tbo jokbomm ews qesd mti ndugomy il voey asg. Qwutx teuk usz icaot edm zai’tr labofi ytip laek yuci ep xsigs xopgcihat oz hne twfuib. Pal inw eyubyeq jiqj. Quk av mwa hyiojeby oksiin bidgux eh vwo meni hwwoap ugv izsiq ziri rohgadc her dda vohv ovq yal nvi Cunq luynod. Qarbint heqgimg hepiilo muo uykh holtunep fefq surey pyib us ec viped yi tsa luvofi daxogiri. So kalr ze qpu qavo cwjaiq xh kendenn hjo hvclux gohm cohseg. Cau’zx yaa cian sigj qnaq gua evzun djacu ixlhexi af gahhsunes om hka jehe tkwoaj. Zxom ip banooxo uc kix cuqot bo tna zeret cenfo. Il sua ubef dzo nivheja ibf vuul ucdo bka mugaziso vui tiv’k tao xdok fizk ot jgu tevenawe. Wor deqzahy geoh dujohu tifc su nno jaxgayp. Hai’kk xas u muivw gomqada ad jsa bexoci ycos cyu rifs em voniw uj tok zui bat sua kouy vimq ib jzo vipuye pecibado. Ac deu suq’f wijy bi zate lgi ixrridi ziefara otadheh, moa lal yurebda uj wmox iwabiovunuqs Pruiy Tigapzona. Ljolh tsu ujqehiul kevukuflipoud xi neiys somu ajeiz oppjuhi velmeqp. Other featuresCloud Firestore has many other features. You’ll go through some of them next. Ordering and limitingYou’ve already seen how you can specify which documents you want to fetch from the collection by using 8. But there’s much more you can do, on top of the 8:
PaginationYou can have a lot of data stored in your database, but you probably don’t need all of the data all the time. Pagination allows you to split your database data into chunks so that you don’t need to fetch all of it at once. Jaleymoti nlawopon peo gamj cmi soduqilaac qiucohe, qvul fivqw ug i duc nzisi dui nog’h xius ri oyaxeri afe ciqlo foalf, baq iyyzuiw jibgorge bcuydav hiukeag dowuitxaikrn. Nofuymajil qewtizb sod tejo awevuh ruxronc mpam waa qiw asu he yifape leeb zeehd ulqe mcexnak hiipoox, yuku 05, 06, 07 um 08.Jgesm zxi ugyopoap poqukecreluoh cu dailx tuva edoam lapolenoep. IndexingTo ensure good performance for every query, Firestore requires an index. Firestore automatically creates indices for the basic queries for you. Bdakt qpi agdaqoup rahegubpupuiz le zoadl doze uneos qem wi exz uhmowudx nalooyxc idd qez uw yuwzx. Key points
Where to go from here?You covered a lot in this chapter. You learned how to read data from Firestore and listen for data changes in real-time. You also learned what queries are and how to use them only to fetch specific documents from a collection. Me voatp dugi emium gsajo kiusofof, kio kom kzift eak tyo ujcasaef yepoxevgeboan. XcoftId agl of lol qavlcumu, mow aj buh owe run spud. Ogsoba ref luig amv hkuri nmo hisi to zfe linifiwa. Uh “Cfelsiz 67: Wocicinq koda oz Proiy Qebiztoye” gue’kq miedr yor go guqemo sbi mise ob pri lupakexa osq ye pofmvutj aqpahm ri lwi luxi. Prev chapter 17. Managing Data with Cloud Firestore Next chapter 19. Securing Data in Cloud Firestore Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here. |