0

I wanna hide a component based on if something happens in another component.

this is my code in app:

function App() {
  const [user] = useAuthState(auth);
  const [hasUsername, setHasUsername] = useState(false);

  if (user) {
    return (
      <div className="App">
        <header>
          <SignOut />
          {hasUsername ? <ShowUsername uid={user.uid} /> : <RegisterUsername />}
        </header>

        <section>{<ChatRoom />}</section>
      </div>
    );
  } else {
    return (
      <div className="App">
        <header></header>

        <section>{<SignIn />}</section>
      </div>
    );
  }
}

and this in show component:

class ShowUsername extends Component {
  constructor(props) {
    super(props);
    this.state = { username: "", uid: this.props.uid };
  }

  async componentDidMount() {
    this.setState({ message: "loading..." });
    const usernameRef = await firestore
      .collection("username")
      .where("uid", "==", this.state.uid)
      .get();

    var username = "Not registered yet";

    usernameRef.docs.map((doc) => {
      if (doc.exists) {
        username = "Logged in as: " + doc.data().username;
        setHasUsername(true); //issue is here
      }
    });

    this.setState({ username: username });
  }

  render() {
    let { username } = this.state;
    return <div>{username}</div>;
  }
}

what I want is that when I call setHasUsername(true) it should change the hasusername to true and show the ShowUsername or RegisterUsername depending if its true or false. what is the best approach to this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
kiba
  • 3
  • 1
  • Your ShowUserName component needs to receive setHasUsername as a prop. You can not call setHasUsername without passing it from App to ShowUserName. – moredrowsy Jun 11 '21 at 16:25

1 Answers1

1

In your App()

// pass your setState function as prop to your child component
{hasUsername ? <ShowUsername uid={user.uid} setHasUsername={setHasUsername} /> : <RegisterUsername />}

In ShowUsername()

this.props.setHasUsername(true); // call the setState from your props
moredrowsy
  • 383
  • 1
  • 13
  • that worked so far. now i need to refresh the page for it to update. is there an easy way to make it update so it checks again if its set to true or false? – kiba Jun 11 '21 at 18:20
  • It should update without page refresh but then again I haven't used class components for a long time. For function components, instead of componentDidMount, you use the hook useEffect to do your async logic there but make sure to perform proper cleanup function. Read this up on the basics of using useEffect. It worked in my previous projects doing something similar to yours. Another similar post to changing components using async in functional components: https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret – moredrowsy Jun 11 '21 at 19:13