I created a context to display the user's email upon logging in using Next.js and Firebase. However, an error occurred when attempting to show the email in the navbar

I keep encountering this issue while attempting to load the page

Error: (0 , lib_AuthContext__WEBPACK_IMPORTED_MODULE_1_.useAuth) is not a function

On a side note, signing in and signing up are functioning correctly

AuthContext.js

"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { onAuthStateChanged, getAuth } from "firebase/auth";
import { auth } from "./firebase";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setUser(user);
    });

    return () => unsubscribe();
  }, []);

  return (
    <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

Navbar.jsx

const { user } = useAuth();
{user ? (
          <span className="navbar-user-email">{user.email}</span>
        ) : (
          <>
            <Link href="/auth/login" className="navbar-link">
              Login
            </Link>
            <Link href="/auth/signup" className="navbar-link">
              Sign Up
            </Link>
          </>
        )}

I have tried numerous solutions but nothing seems to resolve the issue

Answer №1

It appears that you may be unnecessarily nesting the useContext in function calls

Instead of this approach:

export const useAuth = () => useContext(AuthContext);

found in AuthContext.js

You can simply utilize it directly within Navbar.jsx like so:

import {AuthContext} from "./AuthContext"

const { user } = useContext(AuthContext);
{user ? (
    <span className="navbar-user-email">{user.email}</span>
) : (
    <>
        <Link href="/auth/login" className="navbar-link">
            Login
        </Link>
        <Link href="/auth/signup" className="navbar-link">
            Sign Up
        </Link>
    </>
)}

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

Encountered an error in production mode with Angular 7: Uncaught ReferenceError - "environment" variable

During development, my application runs smoothly, and ng build --prod --source-map successfully compiles the application. However, when attempting to access it through the browser, an error occurs: app.module.ts:47 Uncaught ReferenceError: env is not defi ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

Unable to execute app.get in Express framework of Node.js

const express = require('express'); let router = express.Router(); router.get('/create-new', (req, res, next) => { res.send('<form action="/submit-data" method="POST"><input type="text" name="name"><button ...

React application not displaying element properly?

I am facing an issue with my react modal that displays a sign-in and sign-up form. The problem arises when I try to access the button on the form using its id, which is modal-sign-in-submit-button. document.getElementById('modal-sign-in-submit-button ...

React component that enables radio inputs to repeat upon selection

My current project involves creating a quiz app where users can answer single questions using React on Codepen. I am utilizing an API to fetch a question, along with 3 incorrect answers and 1 correct answer, then storing them in the app's state. Howev ...

The delimiting slash is absent between hosts and options

Hello there (I hope my English is not too bad)! Currently, I'm attempting to set up a basic database using MongoDB Atlas (the online alternative), but I am facing an issue at the very first step: connecting! Every time I try, I encounter the same err ...

Navigating to a parent URL where the Angular configuration is set can be achieved by following these steps

My application revolves around a webpage created with the use of node and angular. On the root URL (/), I have incorporated a signup and login form without the use of Angular. Upon successful login, Angular scripts and configuration files are loaded on the ...

Leverage the power of the YouTube API to determine if a video is able to be embedded

As I delve into the YouTube Data API v3 to determine if a particular video is embeddable, I have come across the status.embeddable property that seems crucial. By making a request like this: https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE& ...

Enhance your app with the seamless navigation experience using Ionic 2

As a beginner in Angular2, Ionic2, NodeJS ... I am experimenting with writing some code to learn. In my journey, I attempted to create a screen with 3 tabs and a menuToggle. When the application is launched, clicking the menuToggle button on the first tab ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

Having trouble retrieving the response from Jquery ajax with ajaxoptions

Struggling to utilize jQuery effectively. function fetchData(Id) { var ajaxOptions = { url: 'Api/Client/Get?Id=' + id, type: 'GET', dataType: 'json' }; return $.ajax(ajaxOptions).done().fa ...

Adjust the width of every column across numerous instances of ag-grid on a single webpage

I am facing an issue with Ag-grid tables on my webpage. I have multiple instances of Ag-grid table in a single page, but when I resize the browser window, the columns do not automatically adjust to the width of the table. We are using only one Ag-grid in ...

Enable users to modify the URL in the window.open() function

In the code snippet below, a new window opens when a user clicks on a button: $('.loginButton').click(function () { var strString = $("#medlineSearch").val() var strSearch = "http://google.com&query="; var url = strSearch + strSt ...

Having trouble getting the Random Function to function correctly in Discord.js

I'm working on a piece of code that generates a random value to select two different values from two separate arrays. Every time I run it, however, the result seems to be the same and not truly random. I'm not sure where I went wrong with this. I ...

The primary view seamlessly integrates with the page following the invocation of the partial view

Whenever the button is clicked, a different partial view is returned based on the selected value from the drop-down list. Controller: [HttpPost] public ActionResult Foo(SomeViewModel VM) { var model = VM; if (Request.IsAjaxRequest()) { ...

Vue3 Event Handling - Attempt to access an undefined property while rendering the component

Just starting out with Vue and JavaScript, but making progress! Currently working on a Vue Main App that includes a sub-component for a form (specifically to calculate the difference between 2 values). I want the form values to reset to their initial sta ...

Issue: Having trouble making the frontend work properly due to difficulty in accessing the 'state' property which is undefined

Encountering an issue while attempting to input data from a web application into the database. Having trouble understanding the root cause of the problem. The error occurs when the database insert button is triggered. The following snippets of code showcas ...

PHP Calculator - Displaying results in both the webpage and an Ajax popup for enhanced user experience

UPDATE - the issue was resolved by incorporating $('.popup-with-form').magnificPopup('open'); into the StateChanged function in the JavaScript. Many thanks to @Bollis for the assistance. The Initial Query: I have a basic calculator lo ...

Issues arise when there is excessive tapping on an iPad while incorporating jQuery animate and scrollTop() commands

I am currently in the process of designing a user interface for a web application. The layout I have in mind is similar to what can be found here. $("#scroll-down").on("click", function() { thumbnails.stop(true, true).animate({ scrollTop: &apos ...