Home > Net >  How do I remove the undefined?
How do I remove the undefined?

Time:09-27

If the user does not have a first, middle, or last name, it will show an undefined. How can I remove the underline but instead I will put a saying that it they need to click this link to update their profile enter image description here

import { useSelector } from "react-redux";

const mapState = ({ user }) => ({
  currentUser: user.currentUser,
});

const Settings = () => {
  const { currentUser } = useSelector(mapState);

  const name =
    currentUser?.firstName  
    " "  
    currentUser?.middleName  
    " "  
    currentUser?.lastName;

  return (
    <>
       <Typography>Hello, {name}</Typography>
    </>
  );
};

export default Settings;

CodePudding user response:

import { useSelector } from "react-redux";

const mapState = ({ user }) => ({
  currentUser: user.currentUser,
});

const Settings = () => {
  const { currentUser } = useSelector(mapState);

  const nameComponents = [
    currentUser?.firstName, 
    currentUser?.middleName,
    currentUser?.lastName
  ].filter(part => Boolean(part));
  const name = nameComponents.join(" ")

  return (
    <>
       <Typography>Hello, {name}</Typography>
       { nameComponents.length !== 3 && <button @click="...">
         Fill lackink parts of your name
       </button>}
    </>
  );
};

export default Settings;

CodePudding user response:

You can do a simple checking while rendering Typography component as below

  return (
    <>
       {(
          currentUser?.firstName && 
          currentUser?.middleName && 
          currentUser?.lastName
        ) 
        ? <Typography>Hello, {name}</Typography> 
        : <div>whatever </div>
    </>
  );

CodePudding user response:

Map and/filter the values

Assuming currentUser ONLY has firstName, lastName and middleName

We need more testing if there are roles or addresse etc

const currentUser = { "firstName" : "John", "lastName": "Doe" }

const names = Object.values(currentUser).map(name => name || "");
console.log(names.join(" "))
console.log("Fullname?",names.filter(name => name).length >= 2)

// destructing is not useful here
// const { firstName, middleName, lastName} = currentUser
// console.log(firstName, middleName, lastName)

CodePudding user response:

Use conditions. Return component <Typography>Hello, {name}</Typography> if user has at least all required properties, else redirect to the profile update component.

  • Related