Skip to content
Advertisement

React firebase doesn’t await

I want to get data from firebase and map it and render a table with it but the firebase function returns data after the page loads.

    const [datas, setData] = useState();
    var ref = db.ref("something");

  
    useEffect(() => {
      const fetchData = async () => {
        await ref.once("value").then((snapshot) => {
          const fetched = snapshot.val();
          var feed = {'name':'shoe','remark':'remarka','price':'pricea','photo':'photo','amount':'350'};
          console.log('fetched', fetched)
          setData(feed);
        }); 
      };
      fetchData();
    }, []);

now if I make a var here let’s say var text= datas and console.log it it will return undefined the feed var is just some dummy text

{dummy.map((data, key) => {
//render table
})

is there any way to make the page wait for the function to finish the useState ?

Answer

Use the AND operator (&&) which only executes the right operand when the left operand is truthy. It is not necessary to make a variable called dummy.

{
  datas && datas.map(data=>{
     console.log(data);
  });
}
Advertisement