GithubHelp home page GithubHelp logo

Realtime about supa-fly-stack HOT 3 CLOSED

rphlmr avatar rphlmr commented on May 18, 2024
Realtime

from supa-fly-stack.

Comments (3)

barbinbrad avatar barbinbrad commented on May 18, 2024

There might be a better way to do this, so I wanted to hold off on an MR. But fundamentally, this is what is needed to get realtime + RLS working.

from supa-fly-stack.

rphlmr avatar rphlmr commented on May 18, 2024

Hello, yes you are right.

Support for realtime in this repo has been removed (it is on a branch, outdated: https://github.com/rphlmr/supa-fly-stack/blob/feat/add-supabase-client-provider/app/integrations/supabase/provider.tsx).

I have plans to make improvements but time is missing to work on it right now 🫣

On production, I use an other strategy with a Context provider giving access to accessToken:

//provider

const AuthContext = createContext<{
    accessToken: string | undefined;
}>({ accessToken: undefined });

// in root.tsx, wrap <Outlet /> with <AuthProvider authSession={authSession}> to use access token in supabase'browser client
export const AuthProvider = ({
    children,
    authSession,
}: {
    children: ReactElement;
    authSession: Partial<AuthSession>;
}) => {
    // what root loader data returns
    const { accessToken, expiresIn } = authSession;
    const refresh = useFetcher();

    // trigger a refresh session at expire time. We'll send a post request to our resource route /refresh-session
    useInterval(() => {
        // ask to refresh only if expiresIn is defined
        // prevents trying to refresh when user is not logged in
        if (expiresIn)
            refresh.submit(null, {
                method: "post",
                action: "/refresh-session",
                encType: "application/x-www-form-urlencoded",
            });
    }, expiresIn);

    const value = useMemo(() => ({ accessToken }), [accessToken]);

    return (
        <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
    );
};

export const useAuth = () => {
    const context = useContext(AuthContext);

    if (isBrowser && context === undefined) {
        throw new Error(`useAuth must be used within a AuthProvider.`);
    }

    return context;
};
//route: refresh-session

export async function action({ request }: ActionArgs) {
    const authSession = await refreshAuthSession(request);

    return response.ok(
        { success: true },
        {
            authSession,
        }
    );
}
// in root.tsx
// authSession comes from root loader function
 <AuthProvider authSession={authSession}>
      <Outlet />
 </AuthProvider>
//usage

function useWatchLiveEvents() {
    const { accessToken } = useAuth();
    const revalidate = useRevalidator().revalidate;

    useEffect(() => {
        if (!accessToken) return;

        supabaseClient.realtime.setAuth(accessToken);

        const channel = supabaseClient
            .channel(`db-changes`)
            .on(
                "postgres_changes",
                {
                    event: "DELETE",
                    schema: "public",
                    table: "transaction",
                },
                () => {
                    revalidate();
                }
            )
            .subscribe();

        return () => {
            supabaseClient.removeChannel(channel);
        };
    }, [accessToken, revalidate]);
}

from supa-fly-stack.

barbinbrad avatar barbinbrad commented on May 18, 2024

Ahh that's nice! Thanks for the tip. Closing this.

from supa-fly-stack.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.