Encountering a problem with library functions while attempting to import a module

At the moment, I am utilizing NodeJS.

I have been attempting to import a module into a component function and everything appears to be running smoothly. However, I keep encountering this error in the server console:

error - src\modules\accountFunctions.js (15:35) @ Object.User.GetData
TypeError: _cookieCutter.default.get is not a function

Even though cookieCutter.get is a functioning method and is operating as expected.

import cookieCutter from 'cookie-cutter'
import { useSelector, useDispatch } from 'react-redux'
import { useRouter } from 'next/router'
import { accountActions } from '../store/account'

const Auth = require('./auth.module')

const User = {}

User.GetData = async () => {
    const route = useRouter()
    const userData = useSelector((state) => state.user)
    const dispatch = useDispatch()

    const sessionId = cookieCutter.get('session')

    if (sessionId && userData.username === '') {
        const userExist = await Auth.loadUserInformation()
        if (userExist.result === false) {
            route.push('/login')
            return false
        }
        dispatch(accountActions.updateAccountInformation(userExist.data))
        return true
    } else if (!sessionId) {
        route.push('/login')
        return false
    }
}

module.exports = User

I am aware that one possible solution would be to import the library into the function component, but I am hesitant to continue importing it everywhere.

This is how I am currently importing the module.

import User from '../src/modules/accountFunctions'

const dashboard = () => {
    console.log('Rance')
    User.GetData()
    return <NavBar />;
}

export default dashboard

Answer №1

To ensure that the cookie fetching logic runs correctly on the client-side, it is recommended to move it within a useEffect inside the custom hook. This adjustment will prevent issues with cookieCutter.get not working when Next.js pre-renders the page on the server.

const useUserData = async () => {
    const route = useRouter()
    const userData = useSelector((state) => state.user)
    const dispatch = useDispatch()

    useEffect(() => {
        const getAuthenticatedUser = async () => {   
            const sessionId = cookieCutter.get('session')

            if (sessionId && userData.username === '') {
                const userExist = await Auth.loadUserInformation()
                if (userExist.result === false) {
                    route.push('/login')
                }
                dispatch(accountActions.updateAccountInformation(userExist.data))
            } else if (!sessionId) {
                route.push('/login')
            }
        }
        getAuthenticatedUser()
    }, [])
}

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

The navigation bar is displaying in the inspect element but is mysteriously invisible on the actual webpage

I am encountering an issue with my website while using react and tailwind. When I inspect the element, it shows that my Navbar is present but does not display visually. There are no errors except for a possible issue with Tailwind CSS. Here is the code sni ...

Utilizing the NestJS Reflector within a Custom Decorator: A Comprehensive Guide

I have implemented a solution where I use @SetMetaData('version', 'v2') to specify the version for an HTTP method in a controller. Additionally, I created a custom @Get() decorator that appends the version as a suffix to the controller ...

Struggling to integrate Material UI (MUI) into my React application

I have followed all the necessary steps to install materialUI, emotion/react, and emotion/styled in my react app. However, I am encountering an issue where MUI does not seem to work properly. There are no errors displayed on the console or webpage, but not ...

Grid element's height does not correspond to the responsive square child dimension

In my latest project, I am developing a web application using React and Material-ui. One of the challenges I have encountered is creating a responsive square div for a map component. Unfortunately, attempting to implement a solution from a trick on iamstev ...

Troubleshooting the insertion of post query SQL using the express framework

Hey there! I'm currently working with MYSQL and express for my project. Whenever I attempt to query a POST request, I keep getting this error message: ER_BAD_FIELD_ERROR: Unknown column '$1' in 'field list' I understand that the ...

Unlocking the secrets of extracting frontmatter (meta) from .mdx files in NextJS

After setting up Next.js 13 with TypeScript support and MDX as per the documentation, I am facing a challenge. I have exported frontmatter from one file and want to import it into another. Is this doable? The contents of pages/post.mdx are: export const ...

Obtain the current URL in a Node.js configuration file

In my application using the express framework, I have the following code in my app.js file: var express = require('express'); var app = module.exports = express(); var config = require('./config.js')(app, express); // Including ...

Unusual increase in the Date() function hour on March 12, 2017

I encountered an issue where creating a new Date() object for March 12, 2017 with the hour set to 2am displays as 3am when using getHours(). The expected output should be 2am. Could there be an error in my code? I have highlighted the problematic section ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

Can you explain the distinction between using fallback: false, fallback: true, and blocking in combination with getStaticPaths with and without revalidate in Next.js SSR/ISR

With the release of Next.js 10, the getStaticPaths function now requires the inclusion of the critical fallback key in its returned object, as outlined in the documentation available at: https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key ...

costly API request within the server component for Next.js 13

I am currently working with a server component that looks like this: const ContentSubmissions = async () => { const blogsData: any = await getBlogsData(); const galleryData: any = await getGalleryData(); const questionsData: any = await getQuestio ...

Transforming a JSON file into a new JSON file using an alternative method in React

I have a JSON data structure similar to this example: [ { "quantity": "200", "prodType": "stock", "symbol": "LOL", "prodDesc": "Εθνική τράπεζα", "market": "Greece", "averageCost": "131,16", ...

Try using a different file name instead of index.js as the main page within a directory when working with next.js

When working with Next.js, the usual path to a page looks like this: /pages/blog/index.js However, in Visual Studio Code, this results in all pages displaying as index.js in the tabs, which can make it challenging to keep track of files. Personally, I f ...

What could be causing my useState to return null within my monorepo configuration using vite, react, astro, and nextJS?

I've set up a monorepo with two npm workspaces and everything looks fine on the surface, but it's failing to run properly. Here's how the structure is organized: - package - JSX components to export - vite config - package.json - r ...

Issue: receiving an error message "Error: spawn wslvar ENOENT" while attempting to run yarn storybook on

Currently, I am attempting to follow a tutorial found at The tutorial provides the following set of commands: # Clone the template npx degit chromaui/intro-storybook-react-template taskbox cd taskbox # Install dependencies yarn # Run the test runner (J ...

Combining the power of next.js, styled-components, and react-helmet for seamless website development

Having trouble using both react-helmet and styled-component in conjunction with next.js. The next.js examples demonstrate utilizing each package in separate repositories. Does anyone know how to resolve this issue? ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

What could be the reason behind the "Package.json has missing dependencies" error message in create-react-app?

What's the issue: Recently, I began learning reactjs. In the process of creating a new react app, the build fails and only a package.json file is generated. > PS D:\react-projects> npx create-react-app app-name Creating a new > Reac ...

The object literal can only define existing properties, and the property 'x' is not found in the type (prisma)

Trying to incorporate two new items into a table in my Prisma schema has been challenging. Once I update the database with Prisma DB push and attempt to create new data for the table, issues arise. While everything functions correctly on my localhost, depl ...

Is there a potential issue in Next.js 14 when utilizing the "useClient" function alongside conditional rendering in the app/layout.tsx file?

Within my app, there is a Navbar that will only be visible when the route is either "/" or "/teachers". The Navbar will not appear on the dashboard page ("/dashboard"). I achieved this using conditional rendering in the app/layout.tsx file. "use clien ...