1

I have this higher order function:

Its a supposed to render a based on some props which I am using in conditionals to render my element.

function GenericIsUserLoggedInLink({ isLoggedIn, logOutUser, route, anchorText }) {
 if (isLoggedIn) {
  if (anchorText === undefined) {
   return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
  } else if (anchorText) {
   return <Link href={route}><a>{anchorText}</a></Link>
  } else {
   return null
  }
 } else {
  return  <Link href="/login"><a>Log in!</a></Link>
 }
}

It's getting props from a *Parent class Component, which is getting those props from the redux store.

*link to my repo to checkout the whole file

The above HOC is almost perfect but seems to bork when one tries to log-out for some reason I get this behavior on the left links in the nav.

enter image description here

I began to think maybe the problem is due to the re-rendering and I am not doing anything about it.

I learned recently in a class Component you'd utilized the componentDidUpdate life cycle method when something is changing in the component.

SO I did some digging ad found this post regarding the methods one should use in a HOC. My question is where should it go?

I actually thought of something like this, but it didn't work...

import React, { useEffect } from 'react';

function GenericIsUserLoggedInLink({ isLoggedIn, logOutUser, route, anchorText }) {
 if (isLoggedIn) {
  if (anchorText === undefined) {
   return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
  } else if (anchorText) {
   return <Link href={useEffect(() => {
 {route} // Just took a stab, on second blush I thought it wasn't that crazy!!

}, [route]);}>{anchorText} } else { return null } } else { return Log in! } }

Anyway, I'd just like some insight as to why when you click the logout button the other nav links say login too...

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

0

In your linked code you are using your HOC on your left nav links including your links "Profile" and "Dashboard" and inside your HOC the main condition is:

if (isLoggedIn) {
  ...
} else {
  return  <Link href="/login"><a>Log in!</a></Link>
}

So if you are not logged in (isLoggedin === false) you return a Link with "Log in!" written inside, and that's what get rendered instead of your navlink. It doesn't have much to do with anything else mentioned.

Drax
  • 12,682
  • 7
  • 45
  • 85