Daryl Wong
Daryl Wong

Reputation: 2443

React: React-Firebase-Hooks not getting value

I am using this package React-Firebase-Hooks but I am not very sure how to properly use it.

In my code below, user.data().username is shown correctly but after putting it in useState, the username is not shown. What was not done correctly here?

const [user, loading, error] = useDocument(
  firebase.firestore().collection("users").doc(uid),
  {
    snapshotListenOptions: { includeMetadataChanges: true },
  }
);

const [username, setUsername] = useState(user && user.data().username);

return (
  <div className="flex">
    <div className="w-1/2">
      {user && (
        <div className="p-8">
          <div>{user.data().username}</div>
          <div>{username}</div>
        </div>
      )}
    </div>
    <div className="w-1/2">Box 2</div>
  </div>
);

Upvotes: 1

Views: 540

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

The reason you are not getting the value on state because when the useState is initialized, user doesn't has a value, it's still loading. Since state is initialized only once, when the data from firebase loads, state doesn't changes.
You need to use a useEffect hook to watch for change in user, and setUsername then.

const [user, loading, error] = useDocument(
  firebase.firestore().collection("users").doc(uid),
  {
    snapshotListenOptions: { includeMetadataChanges: true },
  }
);

const [username, setUsername] = useState('');

useEffect(() => {
  if (user) {
    setUsername(user.data().username);
  }
}, [user])

return (
  <div className="flex">
    <div className="w-1/2">
      {user && (
        <div className="p-8">
          <div>{user.data().username}</div>
          <div>{username}</div>
        </div>
      )}
    </div>
    <div className="w-1/2">Box 2</div>
  </div>
);

This should work, if you face any issues, leave a comment.

Upvotes: 1

Related Questions