Search code examples
javascriptreactjsreact-nativemdbootstrap

React error during button click and adding data to database


I'm trying to add data into a database and display it in a table on my front-end at the same time. Adding the data into the database is done by a button click.

The data is added to the database without any problems but when trying to display it in the table I just get some errors.The error picture is here.

The table I'm using looks like this (react bootsrap datatable)

<MDBDataTable
            striped
            small
            data={data}
            tbodyTextWhite
            theadTextWhite
            noBottomColumns
          />

The data variable which is an array looks like this:

const data = {
    columns: [
      //RANDOM COLUMNS HERE
    ],
    rows: tableRowsData(history_numbers_user_database),
  };

Example of output for rows:

    {
      id: "4",
      nr: "50898980",
      service: "ps5",
      id3: "500",
      delete: "yes",
    },
    {
      id: "5",
      nr: "50898980",
      service: "tv",
      id3: "500",
      delete: "yes",
    }

The tableRowsData(history_numbers_user_database) looks like this

const tableRowsData = (database_data) => {
    if (!database_data) {
      return [];
    }

    return database_data;
  };

and the history_numbers_user_database looks like this:

  const history_numbers_user_database = useSelector((state) => {
    console.log(state);
    return state.auth.user ? state.auth.user.history_phone_numbers : "";
  });

On the button click data needs to be added to the history_numbers_user_database (a new row needs to be added to the table as well) in the database and it should be displayed dynamically in the front-end.

The data variable should always be an array and I'm guessing that's why I'm facing this issue but I don't understand how the button click which change the variable type or if it's something related to re-rendering.


Solution

  • const tableRowsData = (database_data) => {
        if (!database_data) {
          return [];
        }
    
        return database_data;
      };
    

    You are calling this function with a string, and in it's second case it just returns what you passed into it. In your history_numbers_user_database selector, it returns an empty string at the end of the ternary.
    So when you call tableRowsData(""), it returns a string, which is not an array, hence .filter is not a function.