SolidJSS
SolidJSโ€ข2y agoโ€ข
3 replies
microsoft

Help understanding createResource

I have a setup like this (LIVE: https://playground.solidjs.com/anonymous/125ef44e-bee8-4049-b17c-166f6042f962)
import { render } from "solid-js/web";
import {
  createSignal,
  createResource,
  onMount,
  Switch,
  Match,
  Suspense,
  For,
  Show,
} from "solid-js";

async function fun(idb: boolean): Promise<string[]> {
  return new Promise((resolve, reject) => {
    if (!idb) return resolve([]);

    setTimeout(() => resolve(["a", "b", "c"]), 500);
  });
}

async function get_idb(): Promise<boolean> {
  return new Promise((resolve) => setTimeout(() => resolve(true), 500));
}

function App() {
  const [idb, setIdb] = createSignal<boolean | null>(null);
  const [res, { refetch }] = createResource(idb, fun);

  onMount(async () => {
    const idb = await get_idb();

    setIdb(idb);
  });

  return (
    <div>
      <h1>Hi</h1>
      <Show when={idb()} fallback={<p>loading idb...</p>}>
        <Suspense fallback={<p>loading things...</p>}>
          <Switch>
            <Match when={res()}>
              <p>things:</p>
              <For each={res()}>{(r) => <p>{r}</p>}</For>
            </Match>
            <Match when={res.error}>
              <p>something went wrong...</p>
              <button onClick={refetch}>try again</button>
            </Match>
          </Switch>
        </Suspense>
      </Show>
    </div>
  );
}

render(() => <App />, document.getElementById("app")!);

I wanted to test out error handling, so I hardcoded a throw in the first request https://playground.solidjs.com/anonymous/121dd55e-bd06-44e9-b36e-ee56585d8ad3

But it doesn't work, and it renders the loading message after it errors out. I tried wrapping it in an error boundary like this, but it still doesn't work, it renders the fallback message, but nothing happens when you click the refetch button https://playground.solidjs.com/anonymous/a29f38e1-9724-43bb-928e-0e7f30ee9f30
Quickly discover what the solid compiler will generate from your JSX template
Quickly discover what the solid compiler will generate from your JSX template
Quickly discover what the solid compiler will generate from your JSX template
Was this page helpful?