Home > Mobile >  Data from function is null on first load
Data from function is null on first load

Time:05-09

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?

CodePudding user response:

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);
};

CodePudding user response:

Try to put a condition, as if(val) then return val....

  • Related