Gintoki
Gintoki

Reputation: 142

showing username in a react component from firebase

im trying to display a username from firebase as a sorta name tag to show what the user is logged in as by searching over their uid. i was read up and said components shouldnt have async in them so i tired to go with following code. however it doesent seem to update, it shows the name correctly in the log but might be from a wrong type. does anyone know what the issue is with this? is the approach even correct?

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

  async componentDidMount() {
    this.setState({ message: "loading..." });
    const snapshot = await firestore
      .collection("username")
      .where("uid", "==", "EwE8qBqjDhNaceqdFEqdxD5X9zu1")
      .get();
    const doc = snapshot.docs.map((doc) => doc.data());
    const username = doc[0].username;
    console.log(username);
    this.setState({ message: username });
  }

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

Upvotes: 0

Views: 63

Answers (1)

user3651521
user3651521

Reputation:

Try this code:

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

  async componentDidMount() {
    this.setState({ message: "loading..." });
    const snapshot = await firestore
      .collection("username")
      .where("uid", "==", "EwE8qBqjDhNaceqdFEqdxD5X9zu1")
      .get();
    const doc = snapshot.docs.map((doc) => doc.data());
    const username = doc[0].username;
    console.log(username);
    this.setState({ username: username });
  }

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

you are supposed to update the state called username, there is no state called message and you were updating that message state and that is why the actual state of username never got updated, so replacing message with username helped and now username state is properly getting updated. I would suggest using firebase listener to update user info.

Upvotes: 1

Related Questions