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.
JavaScript
x
16
16
1
const [datas, setData] = useState();
2
var ref = db.ref("something");
3
4
5
useEffect(() => {
6
const fetchData = async () => {
7
await ref.once("value").then((snapshot) => {
8
const fetched = snapshot.val();
9
var feed = {'name':'shoe','remark':'remarka','price':'pricea','photo':'photo','amount':'350'};
10
console.log('fetched', fetched)
11
setData(feed);
12
});
13
};
14
fetchData();
15
}, []);
16
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
JavaScript
1
4
1
{dummy.map((data, key) => {
2
//render table
3
})
4
is there any way to make the page wait for the function to finish the useState ?
Advertisement
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.
JavaScript
1
6
1
{
2
datas && datas.map(data=>{
3
console.log(data);
4
});
5
}
6