Home > Back-end >  does useloaderdata() in react-router resolve promise?
does useloaderdata() in react-router resolve promise?

Time:01-04

<Route index element={<BlogPostsPage />} loader={blogPostLoader} />

BlogPage

function BlogPostsPage() {
  const posts = useLoaderData() 

  return (
    <>
      <h1>Our Blog Posts</h1>

      <Posts blogPosts={posts} />
    </>
  );
}

export function loader () {
  return getPosts() 
}

getPosts()

export async function getPosts() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  if (!response.ok) {
    throw { message: 'Failed to fetch posts.', status: 500 };
  }
  
  return response.json();
}

My main doubt, since we are returning a promise in a loader function, does useLoaderData() resolve it for us since we aren't awaiting for the data?

It's a doubt which I have.

CodePudding user response:

The useLoaderData hook isn't resolving any Promise returned from a loader function, it's simply returns the (already resolved) value returned from a loader function.

Each route can define a "loader" function to provide data to the route element before it renders. (emphasis mine)

The loader is called prior to the route (and element component) being rendered so by the time the route is rendered, any Promises have already been settled. In other words... all the "awaiting" is done in the loader function and router, the component gets mounted/rendered the the data is immediately available in the component.

CodePudding user response:

useLoaderData does not initiate a fetch. It simply reads the result of a fetch React Router manages internally, so you don't need to worry about it refetching when it re-renders for reasons outside of routing.

You can find more details at: https://reactrouter.com/en/main/hooks/use-loader-data

  • Related