SolidJSS
SolidJS2y ago
26 replies
davidknp

Dynamically creating resources based on reactive state in Solid Store

What would be the right approach to solve this using solids reactivity?

I want to achieve the following fetch the sources (the headings in the picture attached to this message) and then fetch the entities (what is below each of the headings) belonging to each of the sources.

Inspired by the solid-realworld example I was trying to do something like this which doesn't work unfortunately:

Code on Stackblitz

export function StoreProvider(props: any) {
  let sources: any;
  let entities: any;
  const [state, _] = createStore({
    get sources() {
      return sources();
    },
    get entities() {
      return entities();
    },
  });
  sources = createSources();
  entities = createEntities(state);
  return (
    <StoreContext.Provider value={state}>
      {props.children}
    </StoreContext.Provider>
  );
}

function createSources() {
  const [sources] = createResource('idplaceholder', getSources, {
    initialValue: [],
  });
  return sources;
}

function createEntities(state: any) {
  return createMemo(() => {
    let entities = {};
    state.sources.map((s: any) => {
      const [resource] = createResource(s.id, getEntities);
      entities = {
        ...entities,
        [s.id]: {
          get() {
            return resource();
          },
        },
      };
    });
  });
}

function App() {
  const state = useStore();
  return (
    <>
      <div class="sourcewrapper">
        <Suspense fallback={'Loading sources...'}>
          <For each={state.sources}>
            {(item) => <ItemComponent id={item.id} />}
          </For>
        </Suspense>
      </div>
    </>
  );
}

function ItemComponent(props: any) {
  const state = useStore();
  return (
    <div>
      <h2>{props.id}</h2>
      <Suspense fallback={'Loading entities...'}>
        <For each={state.entity[props.id]}>
          {(item) => <div>{item.name}</div>}
        </For>
      </Suspense>
    </div>
  );
}
Goal.png
StackBlitzDavidknp
Next generation frontend tooling. It's fast!
Vitejs - Vite (forked) - StackBlitz
Was this page helpful?