Effect CommunityEC
Effect Community4mo ago
35 replies
sbs

Using Effect-Atom with TanStack Router for authenticated routes

I'm using tanstack router and I am looking to set up some authenticated routes, while trying to lean on effect-atom for all state management. I can do this using
beforeLoad
or go the context route, but just for the sake of it, I'm doing it on beforeLoad. This then requires me to be able to get the value of an atom in an async function. From looking at the API docs i've managed to cobble together something like this:

// app-registry.ts
export const AppRegistry = Registry.make({
  defaultIdleTTL: 400,
  scheduleTask,
});

export async function getResultAtom<T, E>(
  atom: Atom.Atom<Result.Result<T, E>>,
) {
  return await Registry.getResult(atom)(AppRegistry).pipe(
    Effect.runPromiseExit,
  );
}


// main.tsx
const rootElement = document.getElementById("app");
if (rootElement && !rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <StrictMode>
      <RegistryContext.Provider value={AppRegistry}>
        <RouterProvider router={router} />
      </RegistryContext.Provider>
    </StrictMode>,
  );
}


And then I use the getAtomResult utility function in the root route in
beforeLoad
. Is this the recommended way to go about this or is there some more straight-forward way to do this?
Was this page helpful?