Home > front end >  my React context wont work when i try to import it
my React context wont work when i try to import it

Time:10-07

I'm trying to conditionally render the sign-out button based on my context. the problem is that the button always shows. meaning the value is true. but when I hard code them like this it works:

example:

const user=null;
const username=null;

when I do it like this it works but when I import the same values from my context it doesn't. I'm using typescript as well.

here is my context folder :

import { createContext } from "react";
export const UserContext = createContext({ user: null, username: null });

this is the child id like to apply my context:

import Link from "next/link";
import { useContext } from "react";
import { signOut } from "firebase/auth";
import { UserContext } from "../lib/context";
import { auth } from "../lib/firebase";

// Top navbar
export default function Navbar() {
  const { user, username } = useContext(UserContext);

  return (
    <nav className="navbar">
      <ul>
        <li>
          <Link href="/">
            <button className="btn-logo">NXT</button>
          </Link>
        </li>

        {/* user is signed-in and has username */}
        {username && (
          <>
            <li className="push-left">
              <button>Sign Out</button>
            </li>
            <li>
              <Link href="/admin">
                <button className="btn-blue">Write Posts</button>
              </Link>
            </li>
            <li>
              <Link href={`/${username}`}>
                <img src={user?.photoURL || "/hacker.png"} />
              </Link>
            </li>
          </>
        )}

        {/* user is not signed OR has not created username */}
        {!username && (
          <li>
            <Link href="/enter">
              <button className="btn-blue">Log in</button>
            </Link>
          </li>
        )}
      </ul>
    </nav>
  );
}

CodePudding user response:

It show always true because you technically do have a user and username. Their values just happen to be null. Try { username !== null && (...) } { username === null && (...) } maybe that could work for you.

CodePudding user response:

sorry everyone but you was all right the answer was in the provider the value that I had updated in the context provider was a string with '0' therefore returning true

import "../styles/globals.css";
import GetServerSideProps from "next/app";
import type { AppProps } from "next/app";
import Navbar from "../components/Navbar";
import { Toaster } from "react-hot-toast";
import { UserContext } from "../lib/context";
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <UserContext.Provider value={{ user: {}, username: "0" }}>
        <Navbar />
        <Component {...pageProps} />
        <Toaster />
      </UserContext.Provider>
    </>
  );
}

export default MyApp;

given changed it and it reflects on the ui

  • Related