SolidJSS
SolidJS2y ago
ali

How to make fetch request on server before sending html to client?

Hello everyone, I have a question about fetching data. I want to fetch data from an api and send html based on what I fetch.

import { createResource } from "solid-js";

const fetchData = async () => {
  "use server";
  const response = await fetch(
    "http://localhost:5000/api/items?" +
      new URLSearchParams({
        type: "11",
        min: "0",
        max: "1000000",
        polygon:
          "29.00743125000136 59.284420699563725, 13.36290000000119 59.284420699563725, -2.2816312499989806 59.284420699563725, -2.2816312499989806 32.5773969429995, 13.36290000000119 32.5773969429995, 29.00743125000136 32.5773969429995, 29.00743125000136 59.284420699563725",
        polygon2: "",
        itemSort: "new",
      })
  );
  const res = await response.json();
  console.log(res);
  return res;
};

export default function Home() {
  const data = createResource(fetchData);
  console.log(data);

  return <main>{data.toString()}</main>;
}


The way I have it set up now results in the console.log(res); in the async fetchData function giving me the correct result, but the console.log(data); returns this:
[
  [Function: read] { loading: true, error: undefined, state: 'pending' },
  { refetch: [Function: load], mutate: [Function: mutate] }
]


Question: How do I make the sending of the html to the frontend wait until the async function has completed

What I have tried: I have already tried to make the function Home() async. This resulted in the whole component not rendering.

Help would be appreciated!
Was this page helpful?