Next.js Fetching Data Inside Nested Child Component

Viewed 4644

Please consider my circumstance: In Next.js, I have built a component that is intended to be a child component that fetches data on its own (without any parent component) and now I have come to find this is not allowed by the authors of next.js. However, they mention the async-reactor library as a workaround:

May be you can try something like async-reactor

But I tried using async-reactor and was unable to render a fetch inside a nested child component in Next.js still. Here's what I tried:

// my child component 
import React from 'react';
import {asyncReactor} from 'async-reactor';
import fetch from 'isomorphic-unfetch';

function Loader() {

  return (
<div>
    <h2>Loading ...</h2>
</div>
  );
}

async function AsyncPosts() {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await data.json();

  return (
<div>
    <ul>
      {posts.map((x) => <li key={x.id}>{x.title}</li>)}
    </ul>
</div>
  );
}

export default asyncReactor(AsyncPosts, Loader);

I expected this to work but it doesn't render anything except the word "Div" (which isn't even supposed to render "Div").

Is there a way to fetch within a child component in Next.js? Nothing I have tried so far worked but I find it hard to believe this is truly not possible.

1 Answers

As @Arunoda wrote:

We don't have plans to add support for calling getInitialProps in nested components.

The emphasis is on getInitialProps, you can make an ajax request inside any component, but know the benefits / drawback of it.

This ajax request will be implemented inside componentDidMount / useEffect hook which are not called at server-side.

One of the benefits can be lazy loading data, you don't need the entire page's data up front, that means less data => smaller network request.

One drawback can be that this section won't be passed to next's SSR mechanism, therefore won't be easily SEOed.

Related