image.png

1. Fetching data from Next.js (SSR)

When we are doing data fetching from the backend in React, it is done through useState, useEffect and axios. What are supposed to do when the data fetching is supposed to be done from a Server-side component where useState and useEffect are not allowed to pull and depict data.

Solution is to create an asynchronous server-side function that can just await another function that is a wrapper of axios and is fetching the data, and passing it to the main function rendering the ssr components.

//  To perform data fetching in Nex.js on the server-side.

import axios from "axios";

async function fetchData() {
    const response = axios.get('<http://localhost/v1/api/connect/fetch-all?input=a>');
    return response;
}
export default async function User() {
    const data = await fetchData(); 
    <div className="">
        {data}
    </div>
}

2. Loading component

While the data is being fetched through the server side, a good way is to show the user that the data is loading. The way you do this is by adding a loading.tsxin the route navigated folder.

export default function() {
    <div className="">
        loading...
    </div>
}

3. API folder structure

If you want a backend in next.js, the keyword is api inside the root folder app. This is considered as the backend folder of the next.js project.

4. Better fetches → SSR

When you’re using server side rendering, why cant we use direct functions to get data as a backend server from the frontend itself. Instead of doing axios.post(), we can just do await prisma.client.findAll() and retrieve the database.

image.png

5. Singleton for Prisma

When you do prisma.connect() in dev mode, the amount of times you enter Ctrl + S creates a new connection with prisma and that overloads the prisma-db and throws an error. To solve this prisma gave out a db.ts to solve it.

image.png

6. server actions in next.js

Server Actions are a powerful feature introduced in Next.js 13 that allow you to execute server-side code directly from your components, without the need for creating dedicated API routes.