In the context of Next.js, an exported function loses its functionality when utilized in a separate file

Currently, I am delving into NextJs and encountering an issue with utilizing context.

Below is the snippet of my context:

"use client";

import { createContext, useContext, useState } from "react";

const UserAuthContext = createContext();

export function UserAuthWrapper({ children }) {
  const [user, setUser] = useState({ name: "test user" });

  return (
    <UserAuthContext.Provider value={[user, setUser]}>
      {children}
    </UserAuthContext.Provider>
  );
}

export function useUserAuthContext() {
  return useContext(UserAuthContext);
}

However, a problem arises when trying to retrieve the user object using useUserAuthContext. The error message displayed is as follows:

TypeError: (0 , _context_user_auth_context__WEBPACK_IMPORTED_MODULE_2__.useUserAuthContext) is not a function or its return value is not iterable
    at Home (./src/app/page.js:14:93)
    at stringify (<anonymous>)

Shown below is how the UserAuthWrapper is implemented in the RootLayout file:

import { Inter } from "next/font/google";
import "./globals.css";
import { UserAuthWrapper } from "./context/user-auth.context";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <UserAuthWrapper>{children}</UserAuthWrapper>
      </body>
    </html>
  );
}

Here's an example of how I utilize the function:

import { useUserAuthContext } from "./context/user-auth.context";

export default function Home() {
  const [user, setUser] = useUserAuthContext();
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>{user.name}</div>
    </main>
  );
}

Recent Update

============================

I decided to conduct another test on my Home page:

import Image from "next/image";
import { useUserAuthContext } from "./context/user-auth.context";

export default function Home() {
  const a = useUserAuthContext();
  console.log(a);

  const [user, setUser] = useUserAuthContext();
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>{user.name}</div>
    </main>
  );
}

After running this additional test, the error now reads as:

src\app\page.js (5:30) @ useUserAuthContext
 ⨯ TypeError: (0 , _context_user_auth_context__WEBPACK_IMPORTED_MODULE_2__.useUserAuthContext) is not a function
    at Home (./src/app/page.js:14:93)
    at stringify (<anonymous>)
digest: "1948578294"
  3 |
  4 | export default function Home() {
> 5 |   const a = useUserAuthContext();
    |                              ^

Below is the layout of my file/folder structure:

https://i.sstatic.net/g9ui4.png

Answer №1

Encountered a problem while invoking the "use client" function from a server-side script, such as page.tsx

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

What sets the Event and EventHandler apart from each other in terms of functionality?

I am posting this question to gain clarity on the fundamental distinctions and practical applications of the Event versus EvenHandler. ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

Angular - The connections between deeply nested object models are established

I have an Angular application that is used to display company and contact person information in a text box format. Here is the code for displaying the Company Email address: <label> Company Email address</label> <input type="text& ...

Problem arises when a recursive function call is nested within a request in an asynchronous setting

Currently, I am working on the task of finding a specific document path by providing its name as an argument. In the fetch_doc_path function, I am making two get requests to retrieve a JSON file containing information about all files. Subsequently, I recur ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

CORS (Cross-Origin Resource Sharing) Request Failed

Whenever I utilize axios to send a XMLHttpRequest, an error occurs. Error: XMLHttpRequest cannot load . The preflight request is unsuccessful because there is no 'Access-Control-Allow-Origin' header present on the requested resource. Hence, acce ...

Prevent XHR from responding to OPTIONS method

Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handlin ...

jQuery Animation: Creative Menu Icon Display

Whenever the toggle menu's navigation icon is clicked, it triggers an animation that transforms the "hamburger" icon into an "X", causing the navigation menu to drop down. If a user clicks either the navigation icon or outside of the active toggle me ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Steps to deactivate a div in React after a single click

When you click the "show" button for the first time, it displays "hello world" correctly. However, if you click on show again, it should not work. How can I make it so that after one click, it does not hide hello world if you click again? I've tried u ...

Can Express not use await?

Why am I encountering a SyntaxError that says "await is only valid in async function" even though I am using await inside an async function? (async function(){ 'use strict'; const express = require("express"); const bodyParser = ...

How come I am unable to expand a collection of objects using Zustand?

I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message. The structure of the damaged zone object for my car is as follows: const damagedZones ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from ...

Load select box with options upon document load

After the document loads, I want to populate a select box with values from my database using ajax and jQuery. Can someone help me identify what's wrong with my code? <select class="form-control sec" id="sec" name="sec"> <option value="s ...

What are the best practices for implementing cookies in conjunction with context and middleware?

Let's break down the process: User tries to log in using a form If the login is successful, the AuthContext saves a cookie with the accessToken and user profile information A middleware is set up to check the cookie against the identity provider If t ...

The new button placed on a <div> was not initialized to trigger my greasemonkey functions

Recently, I implemented a button via GreaseMonkey: var input = document.createElement('input'); input.type = 'button'; input.value = 'Off'; input.onclick = turnTheWheelsofTime; Initially, the button functioned flawlessly whe ...

Having trouble with your AngularJS ng-repeat functionality?

As a newcomer to AngularJs, I am still grappling with the basics. Currently, I am using the Soundcloud API to retrieve a list of followers for a specific user. In my $scope.init function, I have managed to establish a connection with Soundcloud, authentica ...

The React popup window refuses to close on mobile devices

I am currently facing an issue with a site (a react app) deployed on GitHub pages. The site features cards that, when clicked on, should open a modal/dialog box. Ideally, clicking on the modal should close it. However, I have encountered a problem specific ...