I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request.

The API endpoint follows this structure: /Users/{id}

Additionally, I require assistance in displaying this data on the rendered page.

In the address bar, the link format is as follows: http://localhost:3000/userPage?id=2

Below is how my code looks on the userPage:


import { useRouter } from "next/router";

function GetQuery(){
  const router = useRouter();
  const id = router.query.id;
  return id; 
}

export const getServerSidePros = async (id) =>  {
  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  return {
    props: { users: data },
  };
};

const UserPage = (users) => {
  return (
    <div>
      <h1>Hello</h1>
      <h1>{users.name}</h1>
    </div>
  );
}

I seem to be facing trouble extracting the ID from the URL. Only 'Hello' renders without any additional information.

Furthermore, it appears that the GetQuery function remains unused.

Answer №1

const fetchData = async (context) =>  {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  return {
    props: { usersData: data },
  };
};


const DisplayUserData = ({usersData}) => {
  return (
    <div>
      <h1>Hello</h1>
      <h1>{usersData.name}</h1>
    </div>
  );
}

You are able to utilize context.query within the fetchData function to access the query parameters.

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

Comparing ng-transclude usage: element or attribute styling

Creating a wrapper directive to frame a notification widget within a list is my goal. I plan to transclude specific content based on a property from the 'notif' object into this frame. Currently, I have hardcoded a 'div' element. The i ...

Attempting to streamline this particular JavaScript function

I have been struggling with a function that I believe could be written more effectively. My goal is to simplify it while still maintaining its functionality. function changeLetters(text) { text = text.toLowerCase(); for (var i = 0; i < text.length; ...

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

Using the directive in AngularJS and passing ng-model as an argument

Currently, I am creating a custom directive using AngularJs, and my goal is to pass the ng-model as an argument. <div class="col-md-7"><time-picker></time-picker></div> The directive code looks like this: app.directive(' ...

When setting the Content-Type of an S3 object to 'image/jpeg' in NodeJS, it may appear as 'application/octet' in the S3 console

I am facing an issue with the Content-Type of an image stored in my JPEG buffer. While it uploads and downloads successfully from S3, I encounter errors when trying to send it via the Messenger API programmatically. The S3 console indicates that the actual ...

AngularJS Form Validation Error Handling

I am in the process of implementing Form Validation using AngularJS, and I have come across a scenario involving ng-class that is confusing me. Could someone please explain why they are utilizing ng-class in this manner? The presence of a map and an arra ...

The jssor slider cannot be initialized when it is loaded through ajax requests

Incorporating jQuery's .load() function, my website dynamically loads the HTML code for the jssor slider. To verify the functionality of my code, I have developed a duplicate page which already includes the necessary slider code without utilizing an a ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

What could be the reason the forEachRow function is not impacting the second or subsequent pages within the dhtmlx grid?

I'm trying to format the grid rows as they load. My goal is to have the row appear in red with some conditions. It works correctly for the first page, but not for subsequent pages of the grid. Below is my detailed code. If anyone knows why this is hap ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

Can you provide guidance on how to use Javascript to submit a form specifically when the input name is labeled as "submit"?

Query: How can I use Javascript to submit a form when one of the form inputs is named submit? Scenario: I need to send users to another page using a hidden HTML form. Unfortunately, I cannot modify the names of the inputs in this form because it needs to ...

Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code? var app = angular. ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

Struggling with passing the decoded user ID from Node Express() middleware to a route can be problematic

I have encountered a similar issue to one previously asked on Stack Overflow (NodeJS Express Router, pass decoded object between middleware and route?). In my scenario, I am using the VerifyOrdinaryUser function as middleware in the favorites.js route. Th ...