From dde2ee6b34496ad7f6eb58280690458c28203c2a Mon Sep 17 00:00:00 2001 From: Lucas Alves Date: Tue, 6 Dec 2022 21:37:13 -0300 Subject: [PATCH] Add observable page. --- docs/Advanced/UsingObservables.html | 425 ++++++++++++++++++++++++++++ 1 file changed, 425 insertions(+) create mode 100644 docs/Advanced/UsingObservables.html diff --git a/docs/Advanced/UsingObservables.html b/docs/Advanced/UsingObservables.html new file mode 100644 index 000000000..cd9af392a --- /dev/null +++ b/docs/Advanced/UsingObservables.html @@ -0,0 +1,425 @@ + + + + + + Using observables with watermelondb - WatermelonDB documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + +
+
+

Using observables to + connect your components.

+

You can connect your UI components using observables api or even execute something when the + collection changes. Since collections are a bunch of models you can observe any changes inside those + collections and then do something when it changes.

+

Example

+

+ Given the post example with the following schema: +

+
tableSchema({
+  name: 'posts',
+  columns: [
+    // other columns
+    { name: 'created_at', type: 'number' },
+    { name: 'updated_at', type: 'number' },
+  ]
+}),
+
+

+ Lets write a function to control posts collection when something changes: +

+

+import {database} from '...someplace';
+// Detect any post model change then get the query collection again.
+const postsObservable = database.collections.get('posts').query().observe();
+const unsubscribe =  postsObservable._subscribe({
+    next(records=[]) {
+        // Do something
+    },
+    error(err) {
+      console.error(err);
+    },
+    complete() {
+        console.log('finished');
+    },
+});
+// Then when we don't need it anymore just unsubscribe, call unsubscribe function.
+//unsubscribe(); // Don't forget to call the unsubscribe()
+
+

Keep track of collection count

+

+ In some cases you may need only current collection count, when can write like following to do so: +

+

+// To keep track of posts collection count.
+const postsCountObservable = database.collections.get('posts').query().observeCount();
+const unsubscribe =  postsCountObservable._subscribe({
+    next(newCount) {
+        // Do something
+    },
+    error(err) {
+      console.error(err);
+    },
+    complete() {
+        console.log('finished');
+    },
+});
+
+// Then when we don't need it anymore just unsubscribe, call unsubscribe function.
+// unsubscribe(); // Don't forget to call the unsubscribe()
+
+ + +

Adding within React Components.

+

+ Data and components are fundamental to build react based applications and things can go quite messy since + the database is completely asynchronous and may not respond in component lifecycle. This can be avoided using + ContextApi, Redux or any flavor of global state management tool for querying data in separate + workflow, but it is possible to create a React Hook to query data within React component Lifecycle. +

+

+import {useEffect} from 'react';
+/**
+* Create a custom hook to deal with React component lifecycle and queries.
+*/
+function useWatermelonDbQuery({collection, database,onChange},...query){
+     useEffect(()=>{
+         let isMounted = true;
+         const observable = database.collections.get(collection).query(...query).observe();
+         const unsubscribe = observable._subscribe({
+            next(records = []) {
+              if (isMounted && onChange) {
+                // Check if is still mounted...
+                onChange(records);
+              }
+            },
+            error(err) {
+              console.error(err);
+            },
+            complete() {},
+          });
+
+      return ()=>{
+        isMounted = false;
+        unsubscribe();
+      };
+     },[collection, database,onChange, query]);
+}
+
+// And then in React Component
+import {useState} from 'react';
+const PostList = ()=>{
+  const [posts,setPosts] = useState([]);
+  useWatermelonDbQuery({collection:'posts', database, onChange: (updatedPosts)=>setPosts});
+
+  // Render posts lists.
+  return...
+}
+                    
+
+ + +
+
+ +
+ + + + + + + + + + + + +