Effect CommunityEC
Effect Community•3mo ago•
6 replies
Dominik Vit

Improving Reusable Atom for Sequential RPC Calls

Hi 👋

I am trying to build re-usable atom that accepts multiple component props and does data fetching + some other operations on top of that. I have a working solution but I don't like the family id transformations. How could I improve this? I want to use this if I have multiple sequential RPC calls that depend on each other.
const toFamilyId = (projectId: string, type?: CustomerTypeValue) =>
  projectId + (type ? `-${type}` : '');

const fromFamilyId = (queryKey: string) => {
  const [projectId, type] = queryKey.split('-');
  return {
    projectId: projectId as string,
    type: type ? (Number.parseInt(type, 10) as CustomerTypeValue) : undefined
  };
};

const customersAtom = Atom.family((id: string) =>
  runtime
    .atom(
      Effect.gen(function* () {
        const { projectId, type } = fromFamilyId(id);
        const vrpc = yield* VRpc;
        const customers = yield* vrpc('ListCustomers', {
          projectId
        });
        return customers.filter((customer) =>
          type ? customer.type === type : true
        );
      })
    )
    .pipe(Atom.withReactivity(queryKeys.customer.all))
);
Was this page helpful?