Effect CommunityEC
Effect Community6mo ago
5 replies
Maks

Hydration on the Client (With Effect-RX)

Hey folks.

I faced an issue recently with my state not being preserved on page reload. So I tried implementing it with HydrationBoundary from effect-rx package.

I'm probably doing something wrong. Is there a good example of how to handle such cases?

My scenario:
User logs in successfully, then is navigated to a dashboard page, then reloads the page and gets thrown back to login screen... Ideally, the user should be thrown back to login page as he's just logged in..

I check the locally stored state at the app's entry point like this:

export const GlobalProviders = () => {
  const storedState = getStoredState();
  return (
    <RegistryProvider>
      <HydrationBoundary state={storedState}>
        <StrictMode>
          <AuthSessionManagerWithRouter />
        </StrictMode>
      </HydrationBoundary>
    </RegistryProvider>
  );
};

const AuthSessionManagerWithRouter = () => {
  const session = useRxValue(currentSession);
  const isAuthed = Option.isSome(session);

  return <RouterProvider context={{ isAuthed }} router={router} />;
};


//state.ts
export const currentSession = Rx.make(
  Option.none<CurrentUserAndSessionIdsSchema>(),
).pipe(
  Rx.keepAlive,
);

export const saveStateToStorage = (registry: Registry.Registry) => {
  const dehydratedState = Hydration.dehydrate(registry);
  localStorage.setItem('app-state', JSON.stringify(dehydratedState));
};

export const getStoredState = (): Array<Hydration.DehydratedRx> => {
  const stored = localStorage.getItem('app-state');
  return stored != null ? JSON.parse(stored) : [];
};



As i understand I should dehydrate with smth like this in one of my rx functions?

Effect.gen(function* () {
      const authService = yield* AuthService;
      const registry = yield* Registry.RxRegistry;
      const session = yield* authService.checkSessionEffect();
      dehydratedState(registry);
      registry.set(currentSession, Option.some(session));
      return session;
    }),
Was this page helpful?