Nozbe / withObservables

HOC (Higher-Order Component) for connecting RxJS Observables to React Components
https://github.com/Nozbe/WatermelonDB
MIT License
68 stars 26 forks source link

Downstream updates not working using subscribe #143

Closed jasondavis87 closed 2 months ago

jasondavis87 commented 2 months ago

Hey everyone, I'll start off by saying this is probably more a react thing than a watermelon thing, but i'm not sure which way to go. I've used https://github.com/bndkt/sharemystack and the watermelon docs as a reference and came up with a custom hook:

THE CUSTOM HOOK

"use client";

import { useEffect, useState } from "react";
import { useDatabase } from "@nozbe/watermelondb/hooks";

import type { Post } from "@repo/database";
import { TableName } from "@repo/database";

import { useSync } from "./use-sync";

export function usePost(id: string) {
  const database = useDatabase();
  const sync = useSync();
  const [post, setPost] = useState<Post | null>(null);

  useEffect(() => {
    const sub = database
      .get<Post>(TableName.POSTS)
      .findAndObserve(id)
      .subscribe((data) => {
        console.log("usePost", data);
        setPost(data ?? null);
      });

    return () => sub.unsubscribe();
  }, [database, sync]);

  return { post };
}

USING THE HOOK

"use client";

import { useEffect } from "react";
import { usePost } from "../hooks/usePost";

interface ClientPostPageProps {
  id: string;
}

const ClientPostPage = (props: ClientPostPageProps) => {
  const { id } = props;
  const { post } = usePost(id);

  useEffect(() => {
    console.log("useEffect", post);
  }, [post])

  if (!post) {
    return null;
  }

  return (
    <main>
      Testing
    </main>
  );
}

Any help is appreciated, thanks in advance :)

jasondavis87 commented 2 months ago

Placed on wrong project. moving to watermelondb