Keep Data in Sync with Mutations Using Active Remix Loader Functions

InstructorJon Meyers

Share this video with your friends

Send Tweet

The OAuth flow is asynchronous. This means we get redirected to the landing page before GitHub and Supabase have decided that you can be trusted! πŸ‘

Since our Loader functions get called when we first load the page they make a request to Supabase before receiving a valid access token. This causes RLS to deny the request to select data.

Once our session has been correctly set, Supabase is happy but we aren't telling Remix to fetch this data again. In this lesson, we look at combining the onAuthStateChange hook from Supabase with the useRevalidator hook in Remix to recall any active loaders when the state of our user changes, keeping data in sync with mutations.

Therefore, any time the user's session is updated - the auth flow has completed for either signing in or out - Remix will automatically call all loader functions that are active on the current route (this could be many with nested routing), fetching fresh data from Supabase with a valid access token.

Code Snippets

onAuthStateChange listener

useEffect(() => {
  const {
    data: { subscription },
  } = supabase.auth.onAuthStateChange((event, session) => {
    if (session?.access_token !== serverAccessToken) {
      revalidator.revalidate()
    }
  });

  return () => {
    subscription.unsubscribe();
  };
}, [supabase, serverAccessToken, revalidator]);

Resources

ed leach
~ a year ago

Hi Jon, It is confusing in the useEffect that server session and client session are both called session.

ed leach
~ a year ago

sorry I missed serverAccessToken right there. You can delete these comments.