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

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Iterate through each key in the response JSON object using a variable named "a

Here is a snippet of my code: var roomid= roomIds[i] const Availabilitydata = await AvailResponse.json(); availableroomsArray.push(Availabilitydata); app.get("/api/availability", (req, res) => { res.json({ indicateur: availableroomsA ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Error during live-server npm installation: symlink issue persists even with root/admin privileges

In my current project, I am following a tutorial on AngularJS from the book titled "Unraveling AngularJS 1.5 (With Over 130 Complete Samples" by István Novák, which stipulates the need for installation of Node.js. The appendix of this book provides comma ...

How to ensure that the iframe is completely loaded before proceeding with Selenium JavaScript

I have a webpage that displays an iframe, within the iframe there is a spinning spinner (overlying the fields). My approach involves using selenium to navigate to the iframe, return this.driver.wait(function() { return self.webdriver.until.ableToSw ...

Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed. To achi ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

Creating multiple child processes simultaneously can be achieved by spawning five child processes in parallel

My goal is to simultaneously run five spawn commands. I am passing five hls stream urls to the loop, and these streamlink commands are meant to record the video for 5 seconds before terminating those processes. I have attempted various async methods but a ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

There seems to be a syntax error lurking within npm.js, and for some reason npm insists on utilizing version 10.19.0 of Node.js despite my attempts to update it. The reason behind this behavior

Apologies if this question seems silly, but just a couple of days ago my code was running perfectly fine. Then today when I tried to load it, I encountered all sorts of errors. I am fairly new to node and npm, so I suspect it could be related to version ma ...

Develop a solid foundation for your web application with the perfect combination of ReactJS, Next.js

Currently embarking on a new project where I will be coding with node-express, react, redux, and nextjs. After extensive research online, I have come across numerous examples, but not a single boilerplate that integrates all the necessary pieces for a pro ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Managing authentication within getStaticProps requests

I am working on integrating a NextJs application with its backend in Laravel. Currently, all of our API routes in Laravel are secured using Laravel Sanctum to enhance security and prevent cross-site scripting attacks. One challenge I am facing is that th ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (). I attempted to implement it but encountered some issues. Currentl ...

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...