Reputation: 101
I have this database (realtime/firebase) created using Vue, and now I'd like to retrieve the data using React. I can see the data in the console, but I am unable to render all items, only the last one. This is what I've tried:
const fetchDatabase = () => {
db.on("value", snapshot => {
snapshot.forEach(item => {
let data = item.val();
console.log(data);
setSusi(data);
});
});
};
and I'm trying to render it like this:
<ul>
{Object.entries(susi).map(([key, value]) => {
return (
<li>
{key}: {value}
</li>
);
})}
<hr />
</ul>
<button onClick={fetchDatabase}>pegar anamnese</button>
Upvotes: 1
Views: 354
Reputation: 7418
The problem here is that you set only the last
item to the state:
const fetchDatabase = () => {
db.on("value", snapshot => {
snapshot.forEach(item => {
let data = item.val();
console.log(data);
setSusi(data);
});
});
};
try it with something like this:
const fetchDatabase = () => {
const susis = [];
db.on("value", (snapshot) => {
snapshot.forEach((item) => {
let data = item.val();
console.log(data);
susis.push(data);
});
// here we set all of them
setSusi(susis);
});
};
Upvotes: 1