React-bootstrap-table2 doesn't show data from Firebase

扶醉桌前 提交于 2021-02-11 13:22:21

问题


I've been trying to retrieve data from Firebase Realtime Database and display it in a react-bootstrap-table2, but I've run into some issues when it comes to actually displaying the data. When I run the code no value is printed into the table, however, there is no error in console. If I set the number of displayed values in the table to 25, an error occurs: Uncaught TypeError: Cannot read property 'timestamp' of undefined. However, if I console.log timestamp I first get an empty array and then an array with the timestamped values (see the screenshot below).

Here is my code:

const App = () => {
  const timestamp = [];
  const getTimestamp = () => {
    const database = db.ref().child("timestamped_measures");
    database.on("value", (ts_measures) => {
      ts_measures.forEach((ts_measure) => {
        const array = {
          time: ts_measure.val().timestamp,
        };
        timestamp.push(array);
      });
    });
  };

  const columns = [{ dataField: "time", text: "Timestamp" }];
  useEffect(() => {
    getTimestamp();
  }, []);
  console.log(timestamp);
  return (
    <div className="App">
      <BootstrapTable
        keyField="timestamp"
        data={timestamp}
        columns={columns}
        pagination={paginationFactory()}
      />
    </div>
  );
};

export default App;

This is what my Firebase database looks like

This is what my page and console look like

When the pagination is set from 10 to 25, this is what the error looks like

Does anyone know why my version doesn't work? Any help would be appreciated!


回答1:


Since you are using functional component so make use of hooks for setting state, this will re-render your component after setting your state:

const App = () => {
  // Make timestamp state
  const {timestampList, setTimestampList} = React.useState([]);      

  const timestamp = [];
  const getTimestamp = () => {
    const database = db.ref().child("timestamped_measures");
    database.on("value", (ts_measures) => {
      ts_measures.forEach((ts_measure) => {
        const array = {
          time: ts_measure.val().timestamp,
        };
        timestamp.push(array);
      });
        
        // Set array to timestamp state array
        setTimestampList(timestamp);

    });
  };

  const columns = [{ dataField: "time", text: "Timestamp" }];
  useEffect(() => {
    getTimestamp();
  }, []);
  console.log(timestamp);
  return (
    <div className="App">
      <BootstrapTable
        keyField="timestamp"
        data={timestampList} // Pass timestamp state to data prop
        columns={columns}
        pagination={paginationFactory()}
      />
    </div>
  );
};

export default App;


来源:https://stackoverflow.com/questions/63261651/react-bootstrap-table2-doesnt-show-data-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!