SolidJSS
SolidJS2y ago
14 replies
Carl (klequis)

How to use load property of <Route>

I haven't been able to figure out how to use <Route>'s load function and haven't found a complete example.

One property of props in Person has the data from the fetch but it is still a promise. I'm not sure if it should be and if so, what to do with it.

index.jsx
import { lazy } from "solid-js";
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";
import { loadPerson } from "./route.data";

const Person = lazy(() => import("./pages/Person"))
const Home = lazy(() => import("./pages/Home"))

render(() => (
  <Router>
    <Route path="/" component={Home} />
    <Route
      path="/person"
      load={loadPerson}
      component={Person}
    />
      
  </Router>
), document.getElementById("root"));


route.data.js
import { cache } from "@solidjs/router";

async function fetchPerson() {
  const a = await fetch(`https://swapi.tech/api/people/1/`);
  const b = await a.json();
  console.log("b", b);
  return b;
}

export const loadPerson = cache(async () => {
  const [person] = createResource(() => "", fetchPerson);
  return person;
}, "getUserKey");


Person.jsx
import { createSignal, createResource } from "solid-js";

export default function Person(props) {
  // do I use createResource again?
  const [user] = createResource("", peops.data); // doesn't work

  return (
    <>
      <input
        type="number"
        min="1"
        placeholder="Enter Numeric Id"
        onInput={(e) => setUserId(e.currentTarget.value)}
      />
      <span>{user.loading && "Loading..."}</span>
      <div>
        <pre>{JSON.stringify(user(), null, 2)}</pre>
      </div>
    </>
  );
};
Was this page helpful?