Guide to fetching external data with Next.js and importing the component into a different file

I have implemented the following code in my pages/github file, and when I navigate to localhost:3000/github, the code runs successfully and returns JSON data.

function GithubAPI(props) {
  // Display posts...
  return (<div>{props.data.name}</div>)
}

// This function is invoked during build time
export async function getStaticProps() {
  // Fetch data from an external API endpoint
  const res = await fetch('https://api.github.com/repos/vercel/next.js')

  const data= await res.json()
  console.log(data)

  return {
    props: {
      data,
    },
  }
}

export default GithubAPI

However, when I try to import this component into another one, I encounter some issues.

In my pages/about file

import GithubAPI from './github'
function About(props) {
    console.log(props)

  return (
    <div>
      <div>About</div>
       <GithubAPI/>  {/* TypeError: Cannot read property 'name' of undefined */}

    </div>
  )
}

export default About

I am unsure of how Next.js developers expect us to organize our code in order to make API calls like these and still be able to export components for importing into other parts of the application. How should I structure my code to achieve this?

Answer №1

It is not possible to execute getStaticProps/getServerSideProps within non-page components. It is necessary to pass props instead.

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

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Innovative idea for a time management system based on timelines and scheduling

My latest project involves creating a scrollable scheduler, inspired by vis-timeline and built using Vue.js. One of the main challenges I'm facing is achieving smooth infinite scrolling in all directions (past and future). I must confess that I&apo ...

The Three.js GLSL shader encountered a compilation error

I encountered a compile error message: THREE.WebGLShader: Shader could not compile. I attempted to use shaders from shaderfrog.com, but unfortunately they did not compile correctly. To troubleshoot, I added my new vertex and fragment shaders to the DOM a ...

What is the best way to sort ISO DateTime objects that fall outside of a particular time frame?

I'm currently working on a project that involves a list of objects with properties for startTime and endTime, all in ISO format. Here's a snippet of the list: list = [ { startTime: '2022-06-26T10:00:00.000Z', endTime: '2022- ...

Issue with URL parameter in React when using React Router

Initially, everything was running smoothly in my React project using react-router-dom. However, once I added another Route like so: <Route path="/edit/:id" component={EditPage}/> and tried changing the URL in the browser to http://localhos ...

Minimize a collection of JavaScript objects

I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values. Check out my code snippet below: const data = ...

Using $anchorScroll in Angular to create an anchor link that links to the same page but with a style change seems to be ineffective

I have a simple Angular view that includes a menu. Each item in the menu serves as a link to a specific section of the same page. I am utilizing $anchorScroll to achieve this functionality and it is functioning correctly. However, I am encountering an issu ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Route parameter in JavaScript: only accept numerical values

Is it possible to restrict parameter types to only accept digits? If a letter or other character is inputted, I want to fallback to a default scenario. Below are the two attempts I've made. app.get('/multi/:num?', function (request, respons ...

Unlock the power of TypeScript's inheritance by utilizing static methods for type

In my TypeScript project, I have two classes: BaseModel and HotelModel. The HotelModel extends the BaseModel class, which provides static methods like findById, all, etc. export default class BaseModel { private collection:string _id:string | undefine ...

Explore the possibilities with the latest HIPAA Compliant Tech Stack in Nextjs 13

As I work on developing a web application for a healthcare organization, my top priority is ensuring that all data is stored securely on a HIPAA compliant database and deployed to a HIPAA compliant web hosting service. HIPAA compliance is crucial for pro ...

What is the best method for transferring form data to a string and storing it in localStorage effectively?

Is this the most efficient method for extracting form data into a string and storing it in localStorage? I developed this method independently, but I'm not an experienced programmer. It seems to work for my needs, but I'm unsure if it's com ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

Get user input from a textbox and use that input to conduct a search on Google

Hi there, I'm currently working on solving this particular problem. I'm attempting to create a HTML page using a form where the user can input a keyword and click on the "Search" button to search for that keyword on Google. I haven't had a ...

Analyzing the use of statically imported image files versus path strings for the NextJS Image component

In the process of developing a statically exported website using NextJS (13.5.6), I came across information in the NextJS documentation regarding the Image component. It appears that the "src" parameter has the flexibility to accept either a statically imp ...

Unable to configure node and express for file serving

Currently using Windows 7, I have successfully installed nodes 0.10.12 and the latest versions of express and express-generator globally. I then proceeded to create a new express project called nodetest1 and installed all dependencies using npm install. U ...

Guide on retrieving the response headers with jQuery and AJAX

Connection: keep-alive Content-Length: 2231 Content-Type: text/html; charset=utf-8 Date: Thu, 13 Sep 2018 07:37:46 GMT ETag: W/"8b7-XOXhf04O/VM7yxWQ561PEgxRfz8" x-auth: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YjlhMGEyM2Q0NmI3YjFmYTQzNWI ...

Ensure that only numerical values in decimal form are permitted when entering data in Angular

How can I restrict user input to only decimal values? Here is the HTML code for my input field: <label for="conversion-factor">Conversion Factor:</label> <input type="text" class="form-control form-control-sm" id="conversion-factor" ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...