Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redirects it to the client page. However, I would like to directly fetch the data on the client page itself. I attempted to achieve this using useEffect but encountered an issue where the database data was only returned during a hot reload and not on the initial page load. I hope my question is clear.

This is the code for my server page to fetch the data:

import prisma from "src/libs/prisma";
import RinderListPage from "./page-client";

const Page = async () => {
    let rinder: any = await prisma.rinder.findMany();

    return <RinderListPage rinder={rinder}></RinderListPage>;
};

export default Page;

In addition, I have an API Endpoint containing the data since using Prisma on a client page is not feasible. To attempt fetching the data using useEffect:

useEffect(() => {
    fetch('/api/rinder/list')
      .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [])

Answer №1

If you're looking to showcase your API response before the page fully loads, incorporating a server component is essential. However, if you're working with a client component, utilizing the useEffect hook is the way to go. While the API data is being fetched, displaying a loading screen can provide a seamless user experience.

Another approach to fetching data pre-page load involves transforming your page into a server component and creating a separate file for additional components where you can leverage "useClient" and other relevant parts of your code. This allows you to pass the retrieved API response from 'page.tsx' to child components as props, as I can see you've already implemented.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

Squire.js failing to replace mock dependency while utilizing store

Exploring Squire.js as a dependency loader for RequireJS. Testing in a standard web browser environment to run unit tests. Attempting to utilize store to access my mocks, but struggling with preventing Squire from loading the actual module. The usage of m ...

The regular expressions for Mongodb are functioning properly when running on localhost, but they are not working

I came across the following code snippet: import { User } from "@/mongo"; import { SearchBar, UserRating } from "./components"; type searchParams = { email?: string; }; export default async function Search({ searchParams }: { sea ...

How do I set the initial state to a specific node in xstate?

I'm currently working on a multi-step form that guides users through selecting services, providing contact information, and entering billing details. I have implemented a progress bar and event emissions to track the user's current step using xst ...

Difficulty transmitting Heroku environment variable to Angular CLI application using Node.js

Currently, I am tackling a project that requires passing a stripe key as JSON within Angular. I've stored the key in Heroku config vars and have been attempting to pass that value through the Node.js backend to Angular using the process.env.STRIPE_KE ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar. My choice for the layout is Bootstrap, and I have come acr ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

Rendering HTML is not supported by AngularJS on Android 19 with version 4.4.4 and Safari 8.0.5

I have been working on an AngularJS app that is being displayed in a Webview on Android. Everything was functioning properly until yesterday when I started encountering issues with Angular not rendering the DOM correctly. I have tested the app on various v ...

What is the best way to reassign key-value pairs in JSON mapping using JavaScript/TypeScript?

Given {"a": {"name": "king", "firstname": "Thomas"},"b": {"age": "21"}} I'm exploring a simple way to convert it to {"name": "king","firstname": "Thomas","age": "21"} In the realm of Javascript/Angular. Any helpful suggestions are greatly appreci ...

Rendering the HTML5 canvas within a console environment

I am looking to create images of humans on the console using nodejs. In order to achieve images of higher quality, I require a library or module that can facilitate drawing images in the console. Some options available include imaging and console-png. How ...

CSS: Hover below the designated target to reveal an expanding dropdown menu

My initial solution involved toggling the visibility on and off when hovering. However, this approach is not optimal as the menu should smoothly transition into view. When the visibility is toggled, the user does not experience the intended transition effe ...

Issue of displaying buttons based on sibling's height under certain conditions

OBJECTIVE I have undertaken a project to enhance my skills in React and TypeScript by developing a UI chat interface. The design requirement is that when a chat message has enough vertical space, its action buttons should appear stacked vertically to the ...

Absence of receiving any HTTP error codes when making REST calls

In our application, it is crucial to differentiate between 400 and 500 range error codes for distinct processes. Let's consider three REST calls: The first returns a status code of 200, the second returns 401, and the third returns 502 Initially, ...

The React input field seems to be unresponsive to updates

I'm working on a React/Next application where users can create and update notes/jobs. However, I am facing an issue with my onChange={handleChange} function when trying to edit the input fields. Can anyone point out what might be going wrong? Thank y ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Updating a boolean value from true to false within a Vue component while making an Axios API request

My Vue.js and Axios setup involves making an API call, where I aim to temporarily change the value of a variable from false to true using SetTimeout. However, there seems to be an issue with Vue not responding unless the variable name is hard coded. Withi ...

Which hook should be implemented for automatically updating stock levels after a successful payment on WooCommerce?

When working with WooCommerce, I have implemented my own custom payment method using javascript code. I have successfully retrieved the total amount and passed it to my payment system using the following PHP code: <?php $GLOBALS['cart_total'] ...