0

This is my code

  useEffect(() => {
    console.log('useEffect')
    let database = firebase.database();
    database.ref().on('value', (snapshot) => { 
       console.log('hit'); 
       setQuestions(snapshot.val());
       console.log('questions here ', questions)
    }) 
  }, []);
  console.log(questions);

The output is

undefined
useEffect
undefined
hit
(15) [{...}] //This is questions being logged outside useEffect
questions here undefined

The console.log outputs are all over the place and aren't in order. Which I assume is because js is executed asynchronously. But what I don't get at all is how is the console.log outside useEffect logging questions as (15) [{...}] but then the console.log in useEffect, which is executed after logs questions as undefined. Is there a way I can fix this and make questions equal the array of objects when its logged in useEffect?

cris
  • 265
  • 3
  • 11
  • 1
    _"aren't in order"_ this is what being asynchronous means. You can't use state directly after setting it as setting state is asynchronous – evolutionxbox Apr 05 '21 at 20:12
  • 2
    Does this answer your question? [Reading component state just after setting when using useState hook in react](https://stackoverflow.com/questions/58047171/reading-component-state-just-after-setting-when-using-usestate-hook-in-react) – evolutionxbox Apr 05 '21 at 20:20
  • I think `console.log(questions);` is the other two logs (it gets called on each render) – evolutionxbox Apr 05 '21 at 20:21
  • Asynchronous 101. You order a pizza. The one after useEffect tries to eat the pizza before it is made and delivered. The one inside sits waiting for the doorbell to ring and you can eat the pizza. – epascarello Apr 05 '21 at 20:26

1 Answers1

0

This happens because the console.log under setQuestions, gets executed prior to setQuestions finishing. Therefore it basically shows what questions is before you set it to be snapshot.val().

velez_dot
  • 122
  • 6
  • (I think this question has already [been answered](https://stackoverflow.com/questions/58047171/reading-component-state-just-after-setting-when-using-usestate-hook-in-react)) – evolutionxbox Apr 05 '21 at 20:20