Next.js Discord

Discord Forum

Error: Rendered more hooks than during the previous render.

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hello, I require assistance.

I am using next-auth for authentication, and I'm running into the above issue when I try to fetch data from the client in my page.jsx

Here's my code:
export default function Home() {

  // Data Fetching from Strapi
  function LoggedUser() {
    const [data, setData] = useState(null);
    const [isLoading, setLoading] = useState(true);

    useEffect(() => {
      fetch("http://127.0.0.1:1337/api/users/me", {
        headers: {
        Authorization:
          `Bearer ${session.jwt}`,
      },
      })
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        setLoading(false)
      })
    }, []);

    if (isLoading) return <p>Loading...</p>
    if (!data) return <p>No profile data</p>

    return "Data";

  }
  
  const { data: session, status } = useSession({
    required: true
  })

  if (status === "loading") {
    return (
      <div className="lds-ripple">
        <div></div>
        <div></div>
      </div>
    )
  }

If I remove the nextauth if (status === "loading") check, the fetch works but I can't access the session to get the jwt which I need to pass to the fetch for authenticated requests.

If I remove the fetch then next-auth has no problems but I'm not able to, well, fetch... I've also tried SWR following the docs to the letter, same issue.

I've tried everything I've been able to find online on github, SO and other sites, to no avail... Does anyone have any insight to this issue?
Any help at all would be greatly appreciated ❤️

1 Reply

Spectacled bearOP
Here's the Source of the error according to Next

  29 | // Data Fetching from Strapi
  30 | function LoggedUser() {
> 31 |   const [data, setData] = useState(null);
     |                                   ^
  32 |   const [isLoading, setLoading] = useState(true);
  33 |
  34 |   useEffect(() => {