How to render React providers recursively?

Viewed 259

I have n number of provider components, which are providing context for my MobX stores:

function App({ children }) {
  const owner = createStore(() => OwnerStore);
  const OwnerProvider = useProvider(OwnerStoreID);

  const cat = createStore(() => CatStore);
  const CatProvider = useProvider(CatStoreID);

  return (
    <OwnerProvider value={owner}>
      <CatProvider value={cat}>
        {children}
      </CatProvider>
    </OwnerProvider>
  );
}

However, the number of distinct stores in my application is actually in the dozens, and I don't want to maintain a Christmas tree of nested providers.

I have attempted to write something like this:

const storesConfig = [
  {
    store: OwnerStoreID,
    id: OwnerStoreID,
  },
]

export const StoresProvider = ({ children }) => {
  const createdStores = storesConfig.map((storeConfig) =>
    createStore(() => storeConfig.store)
  )
  const createdProviders = storesConfig.map((storeConfig) =>
    useProvider(storeConfig.id)
  )

  return createdProviders.reduce((Acc, Cur, index) => {
    const child =
      index < createdProviders.length ? (
        <Cur value={createdStores[index]} />
      ) : (
        <Cur value={createdStores[index]}>{children}</Cur>
      )
    if (Acc) {
      return <Acc value={createdStores[index - 1]}>{child}</Acc>
    } else {
      return Cur
    }
  }, null)
}

However, I have run into many indecipherable TypeScript errors. What am I doing wrong? Surely there is a way of recursively assembling a React component tree?

1 Answers

If the errors are from typescript it's probably because typescript can't follow what you are doing (lost track of types somewhere along the way) Try writting the code in javascript and see if that gives you any errors.

Related