Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

javascript - Not getting data from firebase on opening the app

I am trying to get data from firebase but it returns empty value when the app loads, but if I edit something on that file even the commented line, then the data loads and app runs, I want when the app opens all data should be there from firebase to run app. and also how to arrange "grabbedData" in reverse order tried grabbedData.reverse() but doent work.

  const Getdata = async () => {
    let grabbedData = [];

    await firebase
      .database()
      .ref(`/users/`)
      .orderByKey()
      .on("value", (snapshot, key) => {
        // console.log("snapshot....", snapshot);
        grabbedData.push(snapshot.val());
      });
    setUserdata(grabbedData);
    console.log("grabbedData", grabbedData); // empty value here :(
    if (grabbedData) {
      let getfranchiseuid = "";
      Object.keys(grabbedData).map(function (key) {
        let y = grabbedData[key];
        Object.keys(y).map(function (key2) {
          let x = y[key2];
          if (key2 === uid) {
            getfranchiseuid = x.franchiseuid;
          }
        });
      });

      if (getfranchiseuid) {
        let customerList1 = [];
        firebase
          .database()
          .ref(`/serviceProvider/${getfranchiseuid}/franchise/customers`)
          .orderByKey()
          .on("value", (snapshot) => {
            customerList1.push(snapshot.val());
          });
        setCustomerList(customerList1);
        console.log("customerList1customerList1", customerList1);
      }
    }
  };

  useEffect(() => {
    var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
        storeUser({ user });
        setUser(user);
        setEmail(user.email);
        setUid(user.uid);
      } else {
        // No user is signed in.
      }
    });
    unsubscribe();
    Getdata();
  }, []);
question from:https://stackoverflow.com/questions/65644219/not-getting-data-from-firebase-on-opening-the-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Data is loaded from Firebase asynchronously. Since this may take some time, your main JavaScript code will continue to run, so that the user can continue to use the app while the data is loading. Then when the data is available, your callback is invoked with that data.

What this means in your code is that (for example) right now your setUserdata is called before the grabbedData.push(snapshot.val()) has run, so you're setting any empty user data. You can most easily see this by setting some breakpoints on the code and running it in a debugger, or by adding logging and checking the order of its output.

console.log("1");
await firebase
  .database()
  .ref(`/users/`)
  .orderByKey()
  .on("value", (snapshot, key) => {
    console.log("2");
  });
console.log("3");

When you run this code, the output will be:

1

3

2

This is probably not what you expected, but it is exactly correct and does explain your problems.


The solution for this is always the same: any code that needs the data from the database must be inside the callback, or be called from there.

So for example:

await firebase
  .database()
  .ref(`/users/`)
  .orderByKey()
  .on("value", (snapshot, key) => {
    grabbedData.push(snapshot.val());
    setUserdata(grabbedData);
  });

this will ensure that setUserdata is called whenever you updated the grabbedData.


Since you have much more code that depends on grabbedData, that will also have to be inside the callback. So the entire if (grabbedData) { block will need to be moved, and probably others. If you keep applying the solution above, the code will start working.

This is a very common problem for developers that are new to calling asynchronous cloud APIs, so I highly recommend reading some of these other answers:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...