Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data)

export default function IndexPage(props) {
console.log(props.data.copyright);
    return (
        <>
         <div>{props.data.copyright}</div>
        </>
    )
}

export async function getServerSideProps() {
    const res = await fetch(" https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY");
    const data = await res.json();
    return { props: { data } };
}

Update: The code works fine on my local machine and Vercel deployment, but encountering issues on codesandbox.io where I initially started building /feeling frustrated

Answer №1

To successfully retrieve data in React, utilize a React Hook and invoke the function within it. This allows you to store the response in a state for later use.

Here's an example of how you can achieve this:

import fetch from "isomorphic-unfetch";
import React, {useEffect} from "react"

    const IndexPage = props => {
      console.log(props.data);
      if(!props.data){
       return <div>Waiting for data...</div>
      }
      return <div>main page</div>;
    };

    export async function getServerSideProps() {
      const { API_URL } = process.env;
      console.log("inside fetch");
      const res = await fetch(`${API_URL}/movies`);

      const data = await res.json();

      return { props: { data } };
    }

    export default IndexPage;

Alternatively, you can opt for using getStaticProps to ensure that the data is available when the component fetches it.

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

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Despite being deployed on Vercel, the process.env variables in Nextjs are still not functioning as expected

I'm currently working on a project that involves using 4 api keys that I need to keep hidden: STORYBLOK_API_KEY= EMAILJS_SERVICE_ID= EMAILJS_USER_ID= EMAILJS_TEMPLATE_ID= All of these keys are being accessed using process.env.XXX. What's inte ...

Is there a way to include various reactions at once?

I've been searching everywhere for solutions but I'm stuck on this issue. Here's the scenario I'm dealing with: I need my bot to execute a command that will send an embed to a specific channel accessible only by admins. Done. Fol ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

Looking for a way to update a world map image by selecting multiple checkboxes to apply a flood fill color to different countries using Mogrify

Exploring different methods to achieve my goal, I am wondering if creating a web service where users can track visited countries on a world map can be done in a simpler way than using Javascript or Ajax. The idea is for users to mark the countries they hav ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

What are the reasons behind the jQuery file upload failing to work after the initial upload?

I am currently utilizing the jQuery File Upload plugin. To achieve this, I have hidden the file input and set it to activate upon clicking a separate button. You can view an example of this setup on this fiddle. Here is the HTML code snippet: <div> ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

What is the most strategic way to conceal this overlay element?

Currently, the website I'm developing features a series of navigation elements at the top such as "Products" and "Company." Upon hovering over the Products link, an overlay displays a list of products with clickable links. Positioned at the top of the ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

How does a browser decide to load content from an http URL when the frontend source is using an https URL?

When using my Vue component to load external content in an iframe, everything works fine locally. However, once I deploy it to my HTTPS site, I encounter an issue. <iframe src="https://external-site" /> Upon deployment, I receive the following erro ...

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

Ensuring that md-select(s) created through ng-repeat are linked to the same model

<div ng-repeat="(key, value) in dataSet | groupBy: 'partner.partnerName'"> <md-select ng-model="userName" placeholder="{{ key }}" class="partnerUser" > <md-option >{{ key }} </md-option> <md-option ng-repe ...

The state object in Next.js appears to be missing

const [ values , setValues ] = React.useState({ input_type: '', elements: [] }) const addOption = () => { let newElements = values.elements newElements.push({ type: "option", ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

Verifying file types with HTML5 drag and drop feature

Is it possible to change the drop zone's background color to green or red based on whether the dragged payload contains supported file types (JPEG)? Do Gecko and Webkit browsers have the ability to determine the file type of drag and drop files? ...

The Ajax/jQuery output is not showing up in the iframe, but is instead appearing on a separate page

I've scoured various forums and websites, attempting to troubleshoot the issue described below without success. This problem persists in both IE 11 and Firefox 10.0.2. My goal is to submit a form (POST) to a website () and showcase the resulting bri ...