简体   繁体   中英

Importing Library into Next.js Component Issue

I am a little bit confused on my situation. For some odd reason, I am not able to import literally anything into my Nav component. However, I am able to import freely in my other components without any issues.

import { useState, useEffect } from "react";
import styled from "styled-components";
import Link from "next/link";


const Nav = () => {
  
  const [isAuth, setIsAuth] = useState(false);
  const [user, setUser] = useState(null);

  const getUser = async () => {
    const res = await fetch("/api/me");
    const json = await res.json();
    setUser(json);
  };

  useEffect(() => {
    if (user === null || user.message === "FAILED AUTH") {
      setIsAuth(false);
    } else {
      setIsAuth(true);
    }
  }, [user]);

  useEffect(() => {
    getUser();
  }, []);

  const logout = () => {
  
  };

  return (
    <NavWrapper>
      <Home href="/">
        <StyledE>
          E<StyledBlog>BLOG</StyledBlog>
        </StyledE>
      </Home>
      
      <NavLinkWrapper>
        {isAuth ? (
          <LoggedIn>
            <Username>{user.username}</Username>
            <LogoutButton href="/account/login">
              <Logout onClick={logout}>Log Out</Logout>
            </LogoutButton>
          </LoggedIn>
        ) : (
          <LoggedOut>
            <LoginButton href="/account/login">
              <LogIn>Log In</LogIn>
            </LoginButton>
            <SignUpButton href="/account/signup">
              <SignUp>Sign Up</SignUp>
            </SignUpButton>
          </LoggedOut>
        )}
      </NavLinkWrapper>
    </NavWrapper>
  );
};
export default Nav;

This is the error I get when I try to import Cookies from "js-cookie"

error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

My other components import everything just fine....


import styled from "styled-components";
import { useState } from "react";
import Cookies from "js-cookie";


const LoginForm = () => {
  const contentType = "application/json";
  const [loginValue, setLoginValues] = useState({
    username: "",
    password: "",
  });

  const handleLoginChange = (e) => {
    const { name, value } = e.target;
    setLoginValues((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const handleLoginSubmit = (e) => {
    e.preventDefault();
    fetch("/api/auth", {
      method: "POST",
      headers: {
        "Content-Type": contentType,
      },
      body: JSON.stringify(loginValue),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (data && data.error) {
          console.log("FAILED LOGIN");
        }
        if (data && data.token) {
          console.log("Success");
          Cookies.set("token", data.token, { expires: 1 });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <FormWrapper>
      <Form method="POST">
        <Input
          value={loginValue.username}
          type="text"
          name="username"
          placeholder="Username"
          onChange={(e) => handleLoginChange(e)}
        />
        <Input
          value={loginValue.password}
          type="password"
          name="password"
          placeholder="Password"
          onChange={(e) => handleLoginChange(e)}
        />
        <LoginButton type="button" onClick={handleLoginSubmit}>
          Login
        </LoginButton>
      </Form>
    </FormWrapper>
  );
};
export default LoginForm;

It does not give me such error....

Please, does anyone know what the issue is? I have tried everything. Googled all day. But it keeps giving me the same error. And not just the js-cookie library, I literally can not import anything else into this Nav component. Not even other Components...

I think I solved it. For some reason, this specific component requires you to import this way:

const cookies = require("js-cookie")

I am a little bit confused on why.... My other components did not need to do this...

Can someone explain or direct me to why it is like this?

Also, my other form Components are imported into pages.

However, Nav component is imported into a Layout component, which is then wrapped over my _app.js function

const MyApp = ({ Component, pageProps }) => {
  
  return (
    <Layout>
      <Head>
        <title>My Blog</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Component {...pageProps} />
    </Layout>
  );
};

Any direction would be helpful. Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM