What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessly. Would you mind lending your expertise to pinpoint what misstep I may have made? A fresh perspective on this matter would be greatly appreciated. Thank you.

import Head from 'next/head';
import React from 'react';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import styles from '../styles/Home.module.css';


export const getServerSideProps = async () => {

    const movieApi = process.env.TMDB_API_KEY;
  
    const res = await fetch(`https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=${movieApi}&page=1`);
    const movie_data = await res.json();
   
    return {
      props: {
        movies : movie_data
      },
    }
  }


const Form = ({movies}) => {
    console.log(movies); //the value returned is "Undefined"

    const [search, Setsearch] = useState("");

    //Handle input value
    const getLocation = async (e) => {
        // console.log(e.target.value)

        


        e.preventDefault();
      }

    //Handle Submit
    const handleSubmit = (event) =>{
        // console.log("clicked")


        event.preventDefault();
    }

export const getServerSideProps = async () => {

  const movieApi = process.env.TMDB_API_KEY;

  const res = await fetch(`https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=${movieApi}&page=1`);
  const movie_data = await res.json();
 
  return {
    props: {
      movies : movie_data
    },
  }
}


export default function Home({movies}) {
  console.log(movies); //operates perfectly fine
  const [session, loading] = useSession();

  const tmdbMpviesResults = movies.results

Answer №1

In response to your feedback, it seems that <Form /> is not considered a page. This resource on Next.js highlights the issue:

The function getServerSideProps can only be exported from a page. It cannot be exported from non-page files.

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

Monitor changes in the ID attribute and ng-model using $watchCollection

My goal is to utilize the $watchCollection feature in my directive to monitor two specific elements. The first element is the ng-model. The second element is the id attribute. I have successfully implemented separate watches for each of them. retur ...

Encountering a 401 error while attempting to exchange Faceit OAuth authorization code for access token

I am having issues with exchanging a code for a token on the Faceit OAuth. The documentation states the following: Exchanging the Authorization Code for an Access Token The third-party app needs to make a server-to-server call, providing the Authorization ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

Exploring jQuery Mobile: Uncovering the Power of clientX, clientY, and taphold Event

In my current project, I am implementing the taphold event and require the coordinates of the tapped point by the user. However, I have encountered an issue where event.clientX and event.clientY are returning as undefined (you can see the example here: her ...

creating a personalized dropdown menu with react javascript

Is it possible to create a chip in a single select dropdown in React? In a multi-select dropdown, a chip is created as shown in the example below. Can we achieve the same effect in a single selection dropdown? const DropdownExampleClearableMultiple = () = ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

What is the process of invoking a function from a different component in Vue 3?

I attempted to use the $on method and this.$root.$refs.compname_component = this;, but encountered some errors. Please see my code below: formComponent.vue <template> <div v-if="showForm"> create Form </div> </templa ...

Step-by-step guide on utilizing the .change method in order to deactivate a

Can someone help me with a quick solution for this issue? I need to know how to disable a select option once the value has been changed. The option should be available on initial load, but after the user selects it for the first time, it should be disable ...

Convert Ajax null value to NoneType in web2py

Every time I save information on a page, an AJAX request is sent with all the necessary data to be stored in the database. The format of this data looks similar to this example: {type: "cover", title: "test", description: null, tags: null} However, when ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Send information to the next route using Vue

Within my Vue frontend, there is a method called `moveToOrder` which asynchronously communicates with the backend to process a move from the cart collection to the orders collection: methods:{ async moveToOrder() { const res = await this.$axios.g ...

Creating a p5.js circle on top of an HTML image: A step-by-step guide

Currently, I am integrating an image into my web application using standard JavaScript and HTML. The image represents a basic map, and my objective is to utilize p5.js to draw on it. <div id="map"> <img src="Assets/MENA.jpg" ...

Nextjs 13 brings exciting new features, one of which is the ability to call getStatic

I am working on a Next.js 13 application where I have organized my files in the 'app' directory instead of the usual 'pages'. All pages are statically generated during build time and data is fetched from an external API. https://i.sstat ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

Tips for enabling JSON access to the content inside a textarea element in HTML:

I'm attempting to develop a button that enables users to save edits to a post they write in a textarea using JSON. However, when attempting to save the data with a PUT request, I encounter the following error: raise JSONDecodeError("Expecting val ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Retrieve an array from JSON encoding using AJAX

I have been attempting to retrieve 4 JSON arrays stored in a separate file and include them in my main file using an AJAX request. However, I'm facing difficulties storing these arrays into variables and logging them in the console. Here are the resul ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

When a barcode scanner is used, it will trigger a "keypress" event only if the user is currently focused on an input box. Is there a specific event to monitor when the user is not on an input

Scenario: In the development of my web application, I am utilizing a barcode scanner device that allows users to scan barcodes for navigation to specific pages. Challenge: The current barcode scanning device is set up to only trigger "keypress" events w ...

What is the best way to distinguish between enabled buttons using Protractor?

I am facing a challenge with a table containing 20 buttons. Half of these buttons are disabled while the other half is enabled. I am looking for a way to filter out the enabled buttons and click on each of them using a for loop. The buttons that I want to ...