Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance.

I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side.

I understand that using onClick directly is not possible without making it client-side, but I want to avoid doing that.

Below is the code snippet where I am retrieving data straight from the server:

import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React from "react";

const getData = async() => {

    console.log("data from server")
    const response = await get(`posts`)
    return response?.data
}


async function About() {

  const data = await getData();
  
  return ( 
    <div>
      Welcome to About test
      <Button data="posts" />
      {data &&
        data.map((item, index) => {
          return (
            <div key={index}>
              <div>{item.id}</div>
              <div>{item.title}</div>
            </div>
          );
        })}
    </div>
  );
}

export default About;

Answer №1

It seems like the task you are attempting is akin to this scenario:

You must attach a button handler to initiate the function upon clicking, which will then enable you to set an internal component state for rendering the data.

import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React, {useState} from "react";

const fetchData = async() => {
    console.log("retrieving data from server")
    const response = await get(`posts`)
    return response?.data
}

const About = () => {
    const [data, setData] = useState(null)

    const handleClick = async() => {
        const endpointData = await fetchData()
        setData(endpointData)
    }

  return ( 
    <div>
      Welcome to the About page test
      <Button onClick={handleClick} />
      {data &&
        data.map((item, index) => {
          return (
            <div key={index}>
              <div>{item.id}</div>
              <div>{item.title}</div>
            </div>
          );
        })}
    </div>
  );
}

export default About;

However, there is another approach suggested in the comments where you can fetch the data from the server before the page loads and display it without requiring a button click. Optionally, you could store it in a separate state value and load the pre-fetched data on click, functioning as an isVisible state.

import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React from "react";

const fetchData = async () => {
  console.log("retrieving data from server");
  const response = await get(`posts`);
  return response?.data;
};

export async function getServerSideProps() {
  const data = await fetchData();
  return {
    props: {
      data,
    },
  };
}

const About = ({ data }) => {
  return (
    <div>
      Welcome to the About page test
      <Button />
      {data &&
        data.map((item, index) => {
          return (
            <div key={index}>
              <div>{item.id}</div>
              <div>{item.title}</div>
            </div>
          );
        })}
    </div>
  );
};

export default About;

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

What is the process for including a static file on an http server?

Looking to create a chatroom using node.js. Utilizing the socket.io template for this project. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require(&ap ...

Encountering the error message "Uncaught TypeError: $.ajax is undefined"

Recently, I encountered an issue with my form that utilizes ajax to send user information to a php file. The form is embedded within a bootstrap modal and was functioning perfectly until I attempted to add an extra field for enhanced functionality. However ...

How to fetch a single document from a nested array using Mongoose

Currently, I am working on a MongoDB database using Mongoose in Node.js. The collection structure resembles the following: { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz& ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Obtaining the IP address of the client's request

In an effort to prevent others from wasting time in the future, I am sharing this post even though it's not really a question anymore. Objective: Obtain the client IP address and set specific values based on certain octets in the IP address. While w ...

What is preventing me from generating a string for transform:translate within Angular.js?

Attempting a new approach here $scope.graph.transform = "transform: translate(" + $scope.graph.width + "," + $scope.graph.height + ");"; Despite my efforts <h3>transform: <span ng-bind="grap ...

How to efficiently initialize a Next.js app with Phusion Passenger while triggering the production build using a specific file?

In most cases, a Next.js application is launched by using the command npm run start after compiling it with npm run build. I am unable to start it using a command because my web server stack (Phusion Passenger) requires a specific startup script. https:// ...

What is the best way to incorporate lottiefiles for a loading animation on a Next.js project's landing

Is there a way to incorporate the use of lottie in a Next.js project (App Structure) in order to load an animated logo seamlessly? I attempted to include "use client" without success, and also tried importing Lottie from react-lottie as a dynamic import. ...

Ways to restrict the number of times elements are iterated in a `v-for`

Currently developing a compact application using Vuejs 2.0. There are around 15 elements that need to be iterated, but I would like to restrict v-for to only display 5 at a time, with additional buttons for viewing the entire list. Is it feasible to achi ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Is there a way to interact with a DOM element through clicking and then pass it as a variable using PHP?

Is there a way to configure a table so that data from a specific row is sent to a PHP script and displayed in a section on the website when the user clicks on that row? I am looking to pre-fill a data entry form with information from a selected row, allow ...

Iterate through HTML content and utilize JavaScript along with Regular Expressions to substitute specific strings

In my HTML located in Anki, I have the following structure: <p>[!Quote] Title of callout 1<br>Content of callout 1</p> <p>[!Quote] Title of callout 2<br>Content of callout 2</p> <p>[!Quote] Title of callout 3<br ...

Invoke a router inside Node.js once a route has been triggered

I am working with ExpressJS and integrating the Auth0 API for authentication, along with ReactJS on the client side. Due to some limitations of the Auth0 API that I discussed with their team, I have implemented a workaround where I send updated user detail ...

What is the best way to access query string values using JavaScript?

Is it possible to retrieve query string values without using a plugin in jQuery? If the answer is yes, how can this be accomplished? If not, are there any plugins available that can help with this task? ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...

Angular - the utilization of expressions in view templates

Exploring Angular for the first time and attempting to create a Single Page Application (SPA). I have included the route module, which seems to be functioning properly. However, the templates are not interpreting Angular expressions as expected - for examp ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...

Using ng-value does not trigger any updates to the Ng-model

After setting the input value Array property sum, it displays the value in the input field. However, when submitting the form, the Quantity property is not being received in the Order object. I noticed that if I change the value manually, then the Quanti ...

Upon calling the createModalAddPost() function, a single window is triggered to open

Hey there, I'm having a JavaScript question. So, I have a panel that opens a window, and it works fine. But the issue arises when I close the window and try to open it again - it doesn't work. I have to reload the page every time in order to open ...