Home > Enterprise >  React With Same String Comparison Using === Always Evaluates False
React With Same String Comparison Using === Always Evaluates False

Time:10-01

I have a component which uses some state passed down from a parent. The component will render if the user is logged in and a string matches. If so display otherwise dont. I've printed = in to console to ensured the strings had no spaces.

Though the conditional statement is correct "NOT OWNER" still shows when it should be "OWNER".

Here is the component simplified:

import React from "react";

const EditButton= ({
  isUserLoggedIn,
  username,
  sellersUsername,
}) => {
  return (
    <>
      {isUserLoggedIn&& username === sellersUsername? (
        <>OWNER</>
      ) : (
        <>NOT OWNER</>
      )}

      {console.log(`=${isUserLoggedIn}=`)}
      {console.log(`=${username}=`)}
      {console.log(`=${sellersUsername}=`)}
      {console.log(username=== sellersUsername)}
      {console.log(
        username.localeCompare(sellersUsername, "en", {
          sensitivity: "base",
        })
      )}
      {console.log(isUserLoggedIn&&username===sellersUsername)}
    </>
  );
};

export default GalleryEditButton;

The output:

// should evaluate to true but does not
=true=
=RandomTestUsername=
=RandomTestUsername=
false
0
false

Any ideas?

CodePudding user response:

Code example

I tried running a similar scenario on my machine and the results were the ones you'd expect.

My suggestion is try tracking the state update of "username" and "sellersUsername," maybe one of them is not being updated.

The problem is most likely at one of these 2 props since username === sellersUsername is what's returning false.

CodePudding user response:

My suggestion is to check the typeOf the two variables. Because === is a strict checking that is case sensitive and also types sensitive.

  • Related