cs_student_311
cs_student_311

Reputation: 37

Why is useEffect from React not being called?

I don't understand why my useEffect is not being called? I'm following a Youtube tutorial right now and all my code looks exactly the same as in the video. I was reading this: useEffect not being called and not updating state when api is fetched but I couldn't relate it to my problem so I was wondering if anyone could help me on this.

Thanks so much.

import { useSession } from "next-auth/react";
import { ChevronDownIcon } from "@heroicons/react/outline";
import { useEffect, useState } from "react";
import { shuffle } from "lodash";

const colors = [
  "from-indigo-500",
  "from-blue-500",
  "from-green-500",
  "from-red-500",
  "from-yellow-500",
  "from-pink-500",
  "from-purple-500",
];

function Center() {
  const { data: session } = useSession();
  const [color, setColor] = useState(null);

  useEffect(() => {
    console.log("useEffect called");
    setColor(shuffle(colors).pop());
  }, []);

  return (
    <div className="flex-grow">
      <header className="absolute top-5 right-8">
        <div className="flex items-center bg-red-300 space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2">
          <img
            className="rounded-full w-10 h-10"
            src={session?.user.image}
            alt=""
          />
          <h2>{session?.user.name}</h2>
          <ChevronDownIcon className="h-5 w-5" />
        </div>
      </header>

      <section
        className={
          "flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
        }
      >
        <h1>hello</h1>
      </section>
    </div>
  );
}

export default Center;

MRE:

import { useEffect, useState } from "react";

const colors = [
  "from-indigo-500",
  "from-blue-500",
  "from-green-500",
  "from-red-500",
  "from-yellow-500",
  "from-pink-500",
  "from-purple-500",
];

function Center() {
  const [color, setColor] = useState(null);

  useEffect(() => {
    console.log("useEffect called");
  }, []);

  return (
    <div className="flex-grow">
      <section
        className={
          "flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
        }
      >
      </section>
    </div>
  );
}

export default Center;

FINALLY SOLVED!!!

${colors} should've been ${color} and everything in className={} needs to be surrounded by `` not "". I originally thought useEffect() wasn't even been called because I was looking at VSCode terminal instead of chrome console.

Upvotes: 1

Views: 175

Answers (1)

Michael James
Michael James

Reputation: 21

Maybe sounds obvious, but are you sure you didn't filter out your console log from chrome developer tools? The default shows info, warnings and errors but I often filter one and next time I open the console have to reset it.

Upvotes: 2

Related Questions