Reputation: 4253
I'd like to set a value to nickid
state using react hooks.
UID from database has a value, then I set the state and console.log after it, it shows null.
any ideas why?
My code:
const [nickid, setNickid] = useState(null); //uid
useEffect(() => {
firebase.database().ref('/users/').orderByChild('user').equalTo(props.match.params.user).once('value').then(snapshot => {
if (snapshot.exists()){
var uid = Object.keys(snapshot.val())[0]; //uid has a value
setNickid({ nickid: uid });
console.log(nickid); // here is null
Upvotes: 0
Views: 55
Reputation: 58543
First thing setState/setNickid
is async function so you will not get direct that value right after it
Second, change this
setNickid({ nickid: uid });
To
setNickid(uid);
Upvotes: 1
Reputation: 27
setState is async function (does not execute immediately) if you want to console log nickid when it is changed
useEffect(()=>{
console.log(nickid)
},[nickid])
Upvotes: 1