Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data from function is null on first load

I’m using a function from another file to get data from a Firebase. However, the first time I load the app, I don’t get the data. Data pulls it out fine. When I write to the console right after adding it to a variable, I see them. However, Return does not return them and returns only an empty field.

If I edit and save the file after loading, the application is refreshed and the data is loaded. Is this solution correct? Then I want to have more functions there.

const Page = () => {
  const [categories, setCategories] = useState([]);

  const fetchMainCategories = async () => {
    const results = placesB.getMainCategories();
    setCategories(results);
  };

  useEffect(() => {
    fetchMainCategories();
  }, []);

}
export default Page;
class Categories {
    getMainCategories(){
        let val = [];
        const reference = query(ref(db, 'categories/1/'));
        onValue(reference, (snapshot) => {
            val = snapshot.val();
            console.log(val); // It always lists the data here
        });
        return val; // HERE IS THE PROBLEM. On the first load is this empty!
    }
}
const cats = new Categories();
export default cats;

Is here anyone who can help me please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The onValue() returns data asynchronously and hence the array is always returned empty. Since you need to fetch data only once, use get() instead of onValue():

class Categories {
    // async 
    async getMainCategories() {
        const reference = query(ref(db, 'categories/1/'));
        const snap = await get(reference);
        return snap.val();
    }
}

Then you call this method as shown below:

const fetchMainCategories = async () => {
  // await here
  const results = await placesB.getMainCategories();
  console.log(results);
  setCategories(results);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading