Update issue with Material UI table rows when using setState method

Currently, I am facing an issue with passing content to my Material UI table using props. When props are passed explicitly, it works fine. However, I need to retrieve the props from a Firestore database and then pass them to the table. To achieve this, I am utilizing useEffect to fetch the rows upon page load. Unfortunately, when attempting to set the rows using setState, they do not appear on the table component of Material UI.

function Notice () {
  return (
    <div>
      <Table rows= {[{Title: "ABC", A: 1, B: 2, C: 3, D: 4}]} />
    </div>
  );
}

The code above functions perfectly.

function Notice() {
  const [rows, setRows] = useState([]);
  const loadRows = () => {
    getDocs(collection(db, "notice"))
      .then((querySnapshot) => {
        const tempRows = [];
        querySnapshot.forEach((doc) => {
          var fields = doc.data();
          tempRows.push({Title: fields.subject, A: 1, B: 2, C: 3, D: 4});
        });
        setRows(tempRows);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  useEffect(() => {
    loadRows();
  }, []);

  return (
    <div>
      <Table rows={rows} />
    </div>
  );
}

Unfortunately, the example code above does not work as expected. Despite no errors being displayed in the console, the table remains empty. I have attempted moving the loadRows function definition inside useEffect without success. Interestingly, the tempRows object is correctly logged to the console before invoking setState.

function Notice() {
  const [rows, setRows] = useState([]);
  const [newProp, setNewProp] = useState([]);

  const loadRows = () => {
    getDocs(collection(db, "notice"))
      .then((querySnapshot) => {
        const tempRows = [];
        querySnapshot.forEach((doc) => {
          var fields = doc.data();
          tempRows.push({Title: fields.subject, A: 1, B: 2, C: 3, D: 4});
        });
        setRows(tempRows);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  useEffect(() => {
    loadRows();
  }, []);

  useEffect(() => {
    console.log(rows);
    setNewProp(rows);
  }, [rows]);

  return (
    <div>
      <Table rows={newProp} />
    </div>
  );
}

I have also experimented with utilizing two useEffect hooks, where the retrieved rows are successfully printed in the console. Nonetheless, the table continues to remain empty.

Answer №1

Here is an updated version for you to try:

import React, { useState, useEffect } from 'react';
import { collection, getDocs } from 'firebase/firestore';

 function NoticeBoard() {
  const [notices, setNotices] = useState([]);

  useEffect(() => {
    const fetchNotices = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, 'notice'));
        const tempNotices = [];
        querySnapshot.forEach((doc) => {
          var fields = doc.data();
          tempNotices.push({ Title: fields.subject, A: 1, B: 2, C: 3, D: 4 });
        });
        setNotices(tempNotices);
      } catch (error) {
        console.log(error);
      }
    };
    fetchNotices();
  }, []);

 return (
   <div>
     {/* Make sure the Table component receives the notices prop */}
     <Table notices={notices} />
   </div>
 );}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are specific names set aside for JQuery Selectors?

One time, I made a mistake with my selector: $("#cut") Unfortunately, this was not pulling the object correctly even though I had defined an object with that id in the HTML. After changing the object's id (and updating the selector), everything work ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

Discovering the correct location within a complex JSON or array to perform updates using JavaScript (either AngularJS or vanilla JavaScript

I am currently facing a challenge where I need to search for a specific value within my complex JSON array and then update the corresponding object. Here is a snippet of my JSON array: var myArray = [{ "id": 5424, "description": "x ...

What is preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input. The "data" parameter in my submit function is the 'value' attribute of the ngForm. Fo ...

Creating a custom JavaScript library using an existing npm module (codius)

Embarking on a new journey with this, never tried it before. Currently utilizing https://github.com/codius/codius-host. The development of Codiu§ has been abandoned, however I am determined to salvage some parts of it for my own project. It is crucial fo ...

Loop through and display content on the webpage with a for loop

I'm attempting to create a loop that will display information in three different areas of the DOM. Essentially, I have an array of enemies and I want to randomly select three of them to display in separate HTML div classes (firstEnemy, secondEnemy, th ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

What could be causing my JavaScript/jQuery code to malfunction when dealing with checkboxes?

My code is supposed to select and disable checkboxes based on which radio button is clicked. For example, when Zero is selected, all checkboxes should be highlighted and disabled, except for the zeroth checkbox. However, this behavior does not consistent ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

Combining Material-UI themes using concatenation

When working with my material-UI theme, I like to use const to define colors. const tableHeader=grey[400] To maintain semantic constant names, I am trying to create multiple constants that share the same color value. const tableHeader, borderDefault = gre ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Stacking sheets of hole-punched paper on top of one another, create a visually captivating

I am in search of a way to create those distinctive black dots with papers displayed here: body { background: linear-gradient(#ccc, #fff); font: 14px sans-serif; padding: 20px; } .letter { background: #fff; box-shadow: 0 0 10px rgba ...

Update an array while monitoring for a specific event

Working with Ionic, my goal is to push an array of an object when a specific event is emitted. This is what I currently have: export class PublicationService { constructor(private storage: Storage) {} private addPublicationSubject = new Be ...

Whenever the state of a React component is modified, it does not automatically trigger a re

Currently, I am utilizing the React Infinite Scroller library to display a list of posts. Interestingly, my load more results function seems to be triggered three times, resulting in the update occurring thrice (verified through console.log). For renderi ...

Dynamic binding in AngularJS with ng-repeat allows for seamless updating of data

I recently started using a helpful library called Angular Material File input <div layout layout-wrap flex="100" ng-repeat="val in UploadDocuments"> <div flex="100" flex-gt-sm="45"> <div class="md-default-theme" style="margin-le ...

Text is overflowing from the table cell due to its length

UPDATE: I have included a screenshot for reference. My goal is to ensure that the text within the grid container does not scroll horizontally and instead fits within the available space. https://i.stack.imgur.com/CfFuy.png In my React Material-UI table, ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Step-by-step guide to building multiple layouts in React.js using react-router-dom

For my new web application, I am looking to create two distinct layouts based on the user type. If the user is an admin, they should see the dashboard layout, while employees should be directed to the form layout. Initially, only the login page will be dis ...