Why when I console.log(data) is does it log the data but when I try and log the item set by set state its null? I don't understand is it because it doesn't have time to update before console logging?
const [currentUser, setCurrentUser] = useState(null);
const [pending, setpending] = useState(true);
const [userData, setuserData] = useState({});
useEffect(() => {
Authentication.auth().onAuthStateChanged((user) => {
setCurrentUser(user)
setpending(false)
localStorage.setItem('user', user.uid);
console.log(localStorage.getItem('user'));
});
getData()
}, []);
const getData = () => {
Authentication.firestore().collection('Health_data')
.doc(localStorage.getItem('user'))
.get()
.then(doc => {
const data = doc.data();
localStorage.setItem('user_data', JSON.stringify(data));
setuserData(data)
console.log(data)
}).catch(function (error) {
console.error("Error reading health", error);
});
console.log(userData)
}
I'm going to assume you're confused by the output of
console.log(userData);
at the end ofgetData
. There are two reasons why it doesn't show the updated user, either of which would be enough on its own. :-) They are:The
console.log(userData)
happens before thesetuserData
call, because promise callbacks are always asynchronous.userData
is a constant within theExample
function call, its value will not change. When the state is changed,Example
will get called again, and that newuserData
constant will have the updated user in it. (Note that it doesn't matter whether it's declared withlet
orconst
, it's effectively a constant either way.) Each of those constants exists in an execution context that's tied to the specific call toExample
the constant was created in. More in Dan Abramov's article A Complete Guide touseEffect
(which is about much more thanuseEffect
).Here's a demonstration: