How to Fetch data in Dinou with react-enhanced-suspense and Server Functions that return Client Components


Dinou is a React 19 framework. react-enhanced-suspense is a React package that adds extra properties to React’s Suspense.

First thing we need to do is to create a React 19 app by using the command npx create-dinou@latest dinou-app. This will create an app for us ready to be developed in Dinou.

Alternatively, you can create the app yourself from scratch:

  • Create a folder and run the command npm init -y.
  • Install dependencies: npm i react react-dom dinou react-enhanced-suspense.
  • Create a folder src with a page.jsx file in it.
"use client";

export default function Page(){
  return <div>Hi world!</div>
}
Enter fullscreen mode

Exit fullscreen mode

  • Run the project with the command npx dinou dev and go to localhost:3000 in your browser.

In Dinou, Server Functions can return React Client Components. So next thing to do is to create a Server Function that fetches some data and returns a Client Component.

But before that we will create a tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "allowJs": true,
    "noEmit": true
  },
  "include": ["src"]
}
Enter fullscreen mode

Exit fullscreen mode

Now we can import files in Dinou using the alias @/.

Under src/server-functions folder create the Server Function:

"use server";

import Users from "@/components/users";

export async function users(){
  const data = await new Promise((resolve)=>setTimeout(()=>resolve(["John", "Alex"]), 200));

  return <Users users={data} />
}
Enter fullscreen mode

Exit fullscreen mode

Now we have to create the Client Component Users we are returning from the Server Function we’ve just created.

"use client";

export default function Users({users}){
  return users.map(user => <div key={user}>{user}</div>);
}
Enter fullscreen mode

Exit fullscreen mode

Finally, we need to call the Server Function from our component Page with Suspense from react-enhanced-suspense.

"use client";

import Suspense from "react-enhanced-suspense";
import {users} from "@/server-functions/users";

export default function Page(){
  return <div>
    <Suspense resourceId="users">{()=>users()}</Suspense>
  </div>
}
Enter fullscreen mode

Exit fullscreen mode

And that’s it, it will render the React Client Component Users after fetching the data in the Server.



Source link