Skip to content

What is the correct way to use useRouteData #772

@KyleRicardo

Description

@KyleRicardo

I'm following the official guide of Data loading, but I don't use For to show the data. I directly use the data instead:

import { createRouteData, useRouteData } from 'solid-start'

export function routeData() {
  return createRouteData(async () => {
    const response = await fetch('https://hogwarts.deno.dev/students')
    return (await response.json())
  })
}

export default function About() {
  const data = useRouteData<typeof routeData>()
  return (
    <main class="text-center mx-auto text-gray-700 p-4">
      <div>{data()}</div>
    </main>
  )
}

I went to my browser and refresh the page. The content was Undefined Undefined at first, and then became [object Object][object Object] after about 1 second. Why the page is rendered even before the data is ready? Is this the expected behavior?

To make things even worse, when I changed {data()} to {data()[0]}, the page crashed with error TypeError: Cannot read properties of undefined (reading '0') and never came back.

Ok, I thought that was because the data was not ready so I definitely cannot use [0] to get the indexed data.

Fair enough. Then I checked out the other parts of the guide, and found createRouteData. At the end of the page, I got to know I can get the status of the fetching, by access data.loading data.state and data.latest etc. So I changed my code again:

export default function RouteTest() {
  const data = useRouteData<typeof routeData>()
  return (
    <main class="text-center mx-auto text-gray-700 p-4">
      <Show when={data.loading} fallback={<div>{data.latest}</div>} >
        <div>loading</div>
      </Show>
    </main>
  )
}

I refreshed the page and found there was always loading. If I check the data.state, it is always pending, too. So frustrating and wierd.

So, what is the correct way to use this? I really need some help here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions