Fetching related data via an API and rendering it in components via Next.js

105 Views Asked by At

I am dealing with Notion's API to fetch a list of Places and their related City and then rendering this data via some components. I am fairly new to the JS world (2023 edition) so I'm having some trouble figuring out what's the best way to organise this.

This is what I was thinking about:

  • /lib/api.js where I fetch data from Notion's API via their SDK; since the returned data is in a fairly custom format, I map each property that I'm interested in and return a very simplified object. Fetching nested data (a City for every Place) also happens here. In summary, the functions in this file should return what Notion would if it offered a GraphQL API;
  • /pages/[placeId].js where I call the relevant functions in the file above in a getStaticProps and call relevant components from the page itself;
  • /components/text.js where I manipulate the data in a more composable way and render it

This all makes sense until I figure some Notion responses include render information:

{
  "type": "text",
  "text": {
    "content": "This is an ",
    "link": null
  },
  "annotations": {
    "bold": false,
    "italic": false,
    "strikethrough": false,
    "underline": false,
    "code": false,
    "color": "default"
  },
  "plain_text": "This is an ",
  "href": null
}

In this case, it would be strange parsing this and generating the respective HTML inside /lib/api.js. If, on the other hand, I simply return Notion's response in /lib/api.js, I would have to parse properties and request nested information from components, which also doesn't look too nice.

How would one tackle this in a clean, JS-worthy way? I can provide more details if it helps, I tried being as short as possible.

1

There are 1 best solutions below

3
On BEST ANSWER

Rendering html in API doesn't make much sense. Best way is to include that render information in your API response.

If you have deeply nested components, you should use global state management or context API (useContext and Provider) to make the props available.

But since you are using Next.js, you can also use the app directory. You can use the async server rendered components. So, your components are rendered on server side. Also, fetch requests are deduplicated automatically by Next.js, meaning, Next.js will automatically handle caching fetched data. So, you are free to fetch the same data in every nested component without worrying about caching, prop-drilling, etc.