I'm experiencing a challenge with Next.js where I am unable to use return within

My code was functioning properly with if-else statements in run dev, but encountered issues when running build. The if-else statements stopped working, prompting me to explore alternative ways of conditionally rendering a page. A new approach seemed promising, however, the return statement inside is not functioning as expected. It seems to be related to a promise, as replacing it with a console.log successfully outputs text to the console. Can this issue be fixed?

import { useAddress } from "@thirdweb-dev/react";
import Head from 'next/head';
import Link from 'next/link';
import Username from '../components/Username';
import React from "react";

const Home = () => {

    let p = new Promise((resolve, reject) => {
        let address = useAddress();
        if (address) {
            resolve(address)
        } else {
            console.log('no addy')
            reject()
        }
    })
    
    p.then((address) => {
        return (
            <>
                <Head>
                    <title>DRUMM3R</title>
                    <link rel="icon" href="/drum.svg" />
                </Head>
                <Username address={address} />
            </>
        );
    }).catch(() => {
        return (
            <>
                <Head>
                    <title>DRUMM3R</title>
                    <link rel="icon" href="/drum.svg" />                
                </Head>
                <Link href="/">
                    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a>
                </Link>
            </>
        );
    })        
}

export default Home;

Answer №1

One common issue is that React requires a valid JSX element to be returned, but in this case, the function is not returning anything which results in an implicit return of undefined and causing a break in the code.

To resolve this, you can implement some kind of effect (especially if dealing with asynchronous operations) that will trigger a setState and render the appropriate element such as a loading indicator, error message, or data. Alternatively, ensure that the necessary data is already available for the component to render without any issues.

import { useAddress } from "@thirdweb-dev/react";
import Head from "next/head";
import Link from "next/link";
import Username from "../components/Username";
import React from "react";

const Home = () => {
  const address = useAddress();

  return address ? (
<>
  <Head>
    <title>DRUMM3R</title>
    <link rel="icon" href="/drum.svg" />
  </Head>
  <Username address={address} />
</>
  ) : (
<>
  <Head>
    <title>DRUMM3R</title>
    <link rel="icon" href="/drum.svg" />
  </Head>
  <Link href="/">
    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">
      click here to log in
    </a>
  </Link>
</>
  );
};

By making these adjustments, the issue should be resolved.

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

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

Monitor the latest website address being typed into the browser

Is it possible to track the new URL entered by a user in the browser when they leave the current page using the onunload event? For example, if a user is currently on www.xyz.com/page1.aspx and then types a new URL into the browser, I want to capture that ...

Supabase storage encountered an issue while attempting to open the PDF document

After uploading a PDF to Supabase storage, I can easily download it from the dashboard and view it on my local machine or in Chrome. However, when attempting to obtain the public URL either manually by clicking Get Url or programmatically, opening the lin ...

Utilizing both a named function and an arrow function as event handlers in React

Can you spot the issue in the code snippet below? export default function App() { const [count, setCount] = useState(0); return ( <div className="App"> <h2>{count}</h2> <button onClick={() => { ...

Is your event listener failing to activate?

I have been working on a project where I gather array elements from user input and try to display them in an HTML table. Unfortunately, the event listener seems to not be triggering, and I can't figure out why. Here is the relevant HTML code: ...

What is the process for having an object act as a child element?

Currently in the process of learning React/Next.js. A main layout that includes two components - footer and header, has been created. function MainLayout(children) { return( <div> <Header /> {children} ...

The issue of not being able to go fullscreen with a YouTube iframe nested within another iframe

I have a YouTube video embedded inside another iframe, but I am facing an issue where the fullscreen feature is not working even after enabling all the required attributes. If the video isn't displaying properly in the code snippet below, you can vie ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

Step-by-step guide: Adding a Google Maps API key to your WordPress theme

Having an issue with Google Maps on my WordPress website. The error message displayed is: Google Maps API error: MissingKeyMapError I have obtained a Google Maps API key, but I am unsure where to insert it. I am not using a Google Maps plugin; instead, my ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

Implementing the Chakra UI NavBar in a Next.js Project (Troubleshooting Navbar Visibility on the Homepage)

I have a basic understanding of coding, so please consider that. I am working on incorporating a NavBar component into my Next.js app. Initially, I followed a tutorial on building a blog site with Next.js. Despite encountering several errors while adding t ...

Wait to fade in until the fade out process is completely finished

When I click on a button, the old box fades out and the new box fades in. However, I want to ensure that the .fadeIn() only happens once the .fadeOut() is complete. This will prevent two containers from being displayed simultaneously. Any suggestions on ...

Dealing with Cross-Origin Resource Sharing (CORS) problem when using Google Cloud Storage Signed

I'm looking to empower artist clients to easily upload images to Cloud Storage by utilizing Signed URLs. Here's the backend script used to fetch the signed URL, which resides behind a Google Cloud load balancer: (Does the presence of a load bal ...

SlickGrid checkbox formatter/editor experiencing issues with data consistency

Exploring the functionalities of SlickGrid'seditors/formatters, I delved into how these features could potentially alter the data object utilized for constructing the grid (as modifications within the table are usually reflected in the original data o ...

What methods are available for integrating ArcGIS JS into Vue.js?

I have been exploring the examples provided in the documentation for ArcGIS, but I am facing difficulties in using it correctly. For instance, when I try to import Map from ArcGIS as demonstrated in this example: import Map from '@arcgis/Map' I ...

Using the filter function in JavaScript to retrieve specific data

When the user_id from two different data sources matches, I need to return the email from the first source. The first source is a table in PostgreSQL called "results" and the second source is JSON data. I attempted this code snippet: var table = db.query ...

Leveraging Next.js for credential validation along with secured paths using next-auth

Currently in the process of developing a web application using NextJs (13.1.1), I have been provided with an external backend that requires a connection via username/password to obtain an access token, refresh token, and its expiration time in the response ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...