kiliman / remix-flat-routes

Remix package to define routes using the flat-routes convention
MIT License
640 stars 22 forks source link

useRouteLoaderData returns undefined when using flat routes #80

Closed junteudjio closed 8 months ago

junteudjio commented 8 months ago

hi @kiliman , when using remix-flat-routes

I've tested on remix v2.0.1 and remix-flat-routes@0.5.10

kiliman commented 8 months ago

Hmm... I'm not sure why you're having issues. Verify your route ids by dumping useMatches.

// useRouteLoaderData is a simple wrapper around `useMatches`
const useRouteLoaderData(id: string) => useMatches().find(route => route.id === id)
import { json } from '@remix-run/node'
import { useLoaderData, useMatches, useRouteLoaderData } from '@remix-run/react'

export async function loader() {
  return json({ message: 'Hello from users+/_index' })
}

export default function Component() {
  const loaderData = useLoaderData<typeof loader>()
  const parentData = useRouteLoaderData('routes-hybrid/users+/_layout')
  const matches = useMatches()

  return (
    <div>
      <h3>Loader Data</h3>
      <pre>{JSON.stringify(loaderData, null, 2)}</pre>
      <h3>Parent Data</h3>
      <pre>{JSON.stringify(parentData, null, 2)}</pre>
      <h3>Matches</h3>
      <pre>{JSON.stringify(matches, null, 2)}</pre>
    </div>
  )
}
image
junteudjio commented 8 months ago

Sorry @kiliman , Everything works ok. I just realised from reading react-router's docs the following:

The only data available is the routes that are currently rendered. If you ask for data from a route that is not currently rendered, the hook will return undefined.

I did just that and all works fine.

My idea was to emulate React Server Components by creating "resource api routes" and then consuming them from my components.

Thanks again.

kiliman commented 8 months ago

Ah I understand. Yes, the Remix hooks all return data already fetched and stored in the Remix context. If you want to get additional data, you'll need to use the useFetcher hook, or return it from one of your routes' loaders.

junteudjio commented 8 months ago

Indeed. Problem with useFetcher is that I'll have to do it client side and introduce loading state, which I don't want because SEO is paramount for the app I'm building and want as much as possible to happen Server Side.

kiliman commented 8 months ago

Yes, best to do all your fetching in loaders if possible.