Jovane Rocha
Jovane Rocha

Reputation: 101

How to render data (realtime/firebase) in React

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

Answers (1)

Tarik Huber
Tarik Huber

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

Related Questions