My web app returns a empty row in my table

I am building a dynamic editable table with MUI, react.js, node.js and SQL Server. When I visit my web app table, it shows an empty row. I’m new to this, please assist.

It shows me a blank page but it’s meant to display information from my database. Below are my three core files – please I’m confused at this point.

Here is my tablecomponent.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import {
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton,
TextField, Autocomplete
} from '@mui/material';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { useTable, usePagination, useFilters, useSortBy } from 'react-table';
import axios from 'axios'; // Make sure axios is imported
const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India'];
const TableComponent = ({ columns, data }) => {
const [editableRowIndex, setEditableRowIndex] = useState(null);
const [tableData, setTableData] = useState(data);
useEffect(() => {
console.log('tableData:', tableData); // Debug to see if tableData is correctly populated
setTableData(data);
}, [data]);
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
state: { pageIndex },
} = useTable(
{
columns,
data: tableData,
autoResetPage: false,
autoResetFilters: false,
},
useFilters,
useSortBy,
usePagination
);
// Handle edit and save
const handleEditClick = (rowIndex) => {
setEditableRowIndex(rowIndex);
};
const handleSaveClick = async () => {
const row = tableData[editableRowIndex]; // Get the row being edited
try {
// Update the database with the edited row data
await axios.put(`http://localhost:5000/api/data/${row.id}`, row);
// Update the tableData state with the new row data
const updatedData = tableData.map((item, index) => {
if (index === editableRowIndex) {
return row; // Replace the old row with the new updated row
}
return item; // Leave other rows unchanged
});
setTableData(updatedData); // Set the updated data
setEditableRowIndex(null); // Exit edit mode
} catch (error) {
console.error('Error updating data:', error);
}
};
const handleDeleteClick = async (rowIndex) => {
const row = tableData[rowIndex];
try {
await axios.delete(`http://localhost:5000/api/data/${row.id}`);
const updatedData = tableData.filter((_, index) => index !== rowIndex);
setTableData(updatedData);
} catch (error) {
console.error('Error deleting data:', error);
}
};
const handleCancelClick = () => {
setEditableRowIndex(null);
};
const handleCellChange = (e, rowIndex, columnId) => {
const value = e.target.value;
const updatedData = tableData.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnId]: value,
};
}
return row;
});
setTableData(updatedData);
};
const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => {
const updatedData = tableData.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnId]: newValue || '',
};
}
return row;
});
setTableData(updatedData);
};
return (
<TableContainer component={Paper}>
<Table {...getTableProps()} sx={{ minWidth: 650 }}>
<TableHead>
{headerGroups.map(headerGroup => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableCell {...column.getHeaderProps()}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}>
{column.render('Header')}
<span>
{column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</div>
{column.canFilter && (
<IconButton size="small">
<ArrowDropDownIcon />
{column.render('Filter')}
</IconButton>
)}
</div>
</TableCell>
))}
<TableCell>Actions</TableCell>
</TableRow>
))}
</TableHead>
<TableBody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => (
<TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}>
{editableRowIndex === i ? (
cell.column.id === 'country' ? (
<Autocomplete
options={countryOptions}
value={cell.value || ''}
onChange={(event, newValue) =>
handleAutocompleteChange(event, newValue, i, cell.column.id)
}
renderInput={(params) => (
<TextField {...params} variant="outlined" />
)}
/>
) : (
<TextField
value={cell.value}
onChange={(e) => handleCellChange(e, i, cell.column.id)}
variant="outlined"
/>
)
) : (
cell.render('Cell')
)}
</TableCell>
))}
<TableCell>
{editableRowIndex === i ? (
<>
<Button onClick={handleSaveClick}>Save</Button>
<Button onClick={handleCancelClick}>Cancel</Button>
</>
) : (
<>
<Button onClick={() => handleEditClick(i)}>Edit</Button>
<Button onClick={() => handleDeleteClick(i)}>Delete</Button>
</>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
<div style={{ marginTop: '10px' }}>
<Button onClick={previousPage} disabled={!canPreviousPage}>
Previous
</Button>
<span style={{ margin: '0 15px' }}>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<Button onClick={nextPage} disabled={!canNextPage}>
Next
</Button>
</div>
</TableContainer>
);
};
export default TableComponent;
</code>
<code>import React, { useState, useEffect } from 'react'; import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton, TextField, Autocomplete } from '@mui/material'; import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown'; import { useTable, usePagination, useFilters, useSortBy } from 'react-table'; import axios from 'axios'; // Make sure axios is imported const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India']; const TableComponent = ({ columns, data }) => { const [editableRowIndex, setEditableRowIndex] = useState(null); const [tableData, setTableData] = useState(data); useEffect(() => { console.log('tableData:', tableData); // Debug to see if tableData is correctly populated setTableData(data); }, [data]); const { getTableProps, getTableBodyProps, headerGroups, prepareRow, page, nextPage, previousPage, canNextPage, canPreviousPage, pageOptions, state: { pageIndex }, } = useTable( { columns, data: tableData, autoResetPage: false, autoResetFilters: false, }, useFilters, useSortBy, usePagination ); // Handle edit and save const handleEditClick = (rowIndex) => { setEditableRowIndex(rowIndex); }; const handleSaveClick = async () => { const row = tableData[editableRowIndex]; // Get the row being edited try { // Update the database with the edited row data await axios.put(`http://localhost:5000/api/data/${row.id}`, row); // Update the tableData state with the new row data const updatedData = tableData.map((item, index) => { if (index === editableRowIndex) { return row; // Replace the old row with the new updated row } return item; // Leave other rows unchanged }); setTableData(updatedData); // Set the updated data setEditableRowIndex(null); // Exit edit mode } catch (error) { console.error('Error updating data:', error); } }; const handleDeleteClick = async (rowIndex) => { const row = tableData[rowIndex]; try { await axios.delete(`http://localhost:5000/api/data/${row.id}`); const updatedData = tableData.filter((_, index) => index !== rowIndex); setTableData(updatedData); } catch (error) { console.error('Error deleting data:', error); } }; const handleCancelClick = () => { setEditableRowIndex(null); }; const handleCellChange = (e, rowIndex, columnId) => { const value = e.target.value; const updatedData = tableData.map((row, index) => { if (index === rowIndex) { return { ...row, [columnId]: value, }; } return row; }); setTableData(updatedData); }; const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => { const updatedData = tableData.map((row, index) => { if (index === rowIndex) { return { ...row, [columnId]: newValue || '', }; } return row; }); setTableData(updatedData); }; return ( <TableContainer component={Paper}> <Table {...getTableProps()} sx={{ minWidth: 650 }}> <TableHead> {headerGroups.map(headerGroup => ( <TableRow {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <TableCell {...column.getHeaderProps()}> <div style={{ display: 'flex', alignItems: 'center' }}> <div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}> {column.render('Header')} <span> {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''} </span> </div> {column.canFilter && ( <IconButton size="small"> <ArrowDropDownIcon /> {column.render('Filter')} </IconButton> )} </div> </TableCell> ))} <TableCell>Actions</TableCell> </TableRow> ))} </TableHead> <TableBody {...getTableBodyProps()}> {page.map((row, i) => { prepareRow(row); return ( <TableRow {...row.getRowProps()}> {row.cells.map(cell => ( <TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}> {editableRowIndex === i ? ( cell.column.id === 'country' ? ( <Autocomplete options={countryOptions} value={cell.value || ''} onChange={(event, newValue) => handleAutocompleteChange(event, newValue, i, cell.column.id) } renderInput={(params) => ( <TextField {...params} variant="outlined" /> )} /> ) : ( <TextField value={cell.value} onChange={(e) => handleCellChange(e, i, cell.column.id)} variant="outlined" /> ) ) : ( cell.render('Cell') )} </TableCell> ))} <TableCell> {editableRowIndex === i ? ( <> <Button onClick={handleSaveClick}>Save</Button> <Button onClick={handleCancelClick}>Cancel</Button> </> ) : ( <> <Button onClick={() => handleEditClick(i)}>Edit</Button> <Button onClick={() => handleDeleteClick(i)}>Delete</Button> </> )} </TableCell> </TableRow> ); })} </TableBody> </Table> <div style={{ marginTop: '10px' }}> <Button onClick={previousPage} disabled={!canPreviousPage}> Previous </Button> <span style={{ margin: '0 15px' }}> Page{' '} <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </span> <Button onClick={nextPage} disabled={!canNextPage}> Next </Button> </div> </TableContainer> ); }; export default TableComponent; </code>
import React, { useState, useEffect } from 'react';
import {
  Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton,
  TextField, Autocomplete
} from '@mui/material';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { useTable, usePagination, useFilters, useSortBy } from 'react-table';
import axios from 'axios'; // Make sure axios is imported

const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India'];

const TableComponent = ({ columns, data }) => {
  const [editableRowIndex, setEditableRowIndex] = useState(null);
  const [tableData, setTableData] = useState(data);

  useEffect(() => {
    console.log('tableData:', tableData); // Debug to see if tableData is correctly populated
    setTableData(data);
  }, [data]);
  
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    nextPage,
    previousPage,
    canNextPage,
    canPreviousPage,
    pageOptions,
    state: { pageIndex },
  } = useTable(
    {
      columns,
      data: tableData,
      autoResetPage: false,
      autoResetFilters: false,
    },
    useFilters,
    useSortBy,
    usePagination
  );

  // Handle edit and save
  const handleEditClick = (rowIndex) => {
    setEditableRowIndex(rowIndex);
  };

  const handleSaveClick = async () => {
    const row = tableData[editableRowIndex]; // Get the row being edited
    try {
      // Update the database with the edited row data
      await axios.put(`http://localhost:5000/api/data/${row.id}`, row);
  
      // Update the tableData state with the new row data
      const updatedData = tableData.map((item, index) => {
        if (index === editableRowIndex) {
          return row; // Replace the old row with the new updated row
        }
        return item; // Leave other rows unchanged
      });
  
      setTableData(updatedData); // Set the updated data
      setEditableRowIndex(null); // Exit edit mode
  
    } catch (error) {
      console.error('Error updating data:', error);
    }
  };
  
  const handleDeleteClick = async (rowIndex) => {
    const row = tableData[rowIndex];
    try {
      await axios.delete(`http://localhost:5000/api/data/${row.id}`);
      const updatedData = tableData.filter((_, index) => index !== rowIndex);
      setTableData(updatedData);
    } catch (error) {
      console.error('Error deleting data:', error);
    }
  };

  const handleCancelClick = () => {
    setEditableRowIndex(null);
  };

  const handleCellChange = (e, rowIndex, columnId) => {
    const value = e.target.value;
    const updatedData = tableData.map((row, index) => {
      if (index === rowIndex) {
        return {
          ...row,
          [columnId]: value,
        };
      }
      return row;
    });
    setTableData(updatedData);
  };

  const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => {
    const updatedData = tableData.map((row, index) => {
      if (index === rowIndex) {
        return {
          ...row,
          [columnId]: newValue || '',
        };
      }
      return row;
    });
    setTableData(updatedData);
  };

  return (
    <TableContainer component={Paper}>
      <Table {...getTableProps()} sx={{ minWidth: 650 }}>
        <TableHead>
          {headerGroups.map(headerGroup => (
            <TableRow {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <TableCell {...column.getHeaderProps()}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}>
                      {column.render('Header')}
                      <span>
                        {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
                      </span>
                    </div>
                    {column.canFilter && (
                      <IconButton size="small">
                        <ArrowDropDownIcon />
                        {column.render('Filter')}
                      </IconButton>
                    )}
                  </div>
                </TableCell>
              ))}
              <TableCell>Actions</TableCell>
            </TableRow>
          ))}
        </TableHead>
        <TableBody {...getTableBodyProps()}>
          {page.map((row, i) => {
            prepareRow(row);
            return (
              <TableRow {...row.getRowProps()}>
                {row.cells.map(cell => (
                  <TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}>
                    {editableRowIndex === i ? (
                      cell.column.id === 'country' ? (
                        <Autocomplete
                          options={countryOptions}
                          value={cell.value || ''}
                          onChange={(event, newValue) =>
                            handleAutocompleteChange(event, newValue, i, cell.column.id)
                          }
                          renderInput={(params) => (
                            <TextField {...params} variant="outlined" />
                          )}
                        />
                      ) : (
                        <TextField
                          value={cell.value}
                          onChange={(e) => handleCellChange(e, i, cell.column.id)}
                          variant="outlined"
                        />
                      )
                    ) : (
                      cell.render('Cell')
                    )}
                  </TableCell>
                ))}
                <TableCell>
                  {editableRowIndex === i ? (
                    <>
                      <Button onClick={handleSaveClick}>Save</Button>
                      <Button onClick={handleCancelClick}>Cancel</Button>
                    </>
                  ) : (
                    <>
                      <Button onClick={() => handleEditClick(i)}>Edit</Button>
                      <Button onClick={() => handleDeleteClick(i)}>Delete</Button>
                    </>
                  )}
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
      <div style={{ marginTop: '10px' }}>
        <Button onClick={previousPage} disabled={!canPreviousPage}>
          Previous
        </Button>
        <span style={{ margin: '0 15px' }}>
          Page{' '}
          <strong>
            {pageIndex + 1} of {pageOptions.length}
          </strong>{' '}
        </span>
        <Button onClick={nextPage} disabled={!canNextPage}>
          Next
        </Button>
      </div>
    </TableContainer>
  );
};  

export default TableComponent; 

Here is my

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import TableComponent from './TableComponent';
import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined
import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined
import axios from 'axios';
const columns = [
{
Header: 'Name',
accessor: 'name',
Filter: DropdownTextFilter,
},
{
Header: 'Age',
accessor: 'age',
Filter: DropdownNumberFilter,
},
{
Header: 'Country',
accessor: 'country',
Filter: DropdownTextFilter,
},
];
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/api/data')
.then(response => {
console.log(response.data); // Check if data is fetched correctly
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div>
<h1>Custom Filter Table with Actions</h1>
<TableComponent columns={columns} data={data} />
</div>
);
}
export default App;
</code>
<code>import React, { useState, useEffect } from 'react'; import TableComponent from './TableComponent'; import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined import axios from 'axios'; const columns = [ { Header: 'Name', accessor: 'name', Filter: DropdownTextFilter, }, { Header: 'Age', accessor: 'age', Filter: DropdownNumberFilter, }, { Header: 'Country', accessor: 'country', Filter: DropdownTextFilter, }, ]; function App() { const [data, setData] = useState([]); useEffect(() => { axios.get('http://localhost:5000/api/data') .then(response => { console.log(response.data); // Check if data is fetched correctly setData(response.data); }) .catch(error => { console.error('Error fetching data:', error); }); }, []); return ( <div> <h1>Custom Filter Table with Actions</h1> <TableComponent columns={columns} data={data} /> </div> ); } export default App; </code>
import React, { useState, useEffect } from 'react';
import TableComponent from './TableComponent';
import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined
import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined
import axios from 'axios';

const columns = [
  {
    Header: 'Name',
    accessor: 'name',
    Filter: DropdownTextFilter,
  },
  {
    Header: 'Age',
    accessor: 'age',
    Filter: DropdownNumberFilter,
  },
  {
    Header: 'Country',
    accessor: 'country',
    Filter: DropdownTextFilter,
  },
];

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:5000/api/data')
      .then(response => {
        console.log(response.data); // Check if data is fetched correctly
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>Custom Filter Table with Actions</h1>
      <TableComponent columns={columns} data={data} />
    </div>
  );
}

export default App;

Here is my serve.js file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// backend/server.js
const express = require('express');
const sql = require('mssql');
const app = express();
const PORT = 5000;
const cors = require('cors');
app.use(cors());
app.use(express.json());
const pool = new sql.ConnectionPool({
user: 'sa',
password: 'password',
server: 'DESKTOP-OA96LT5',
database: 'mydynamicDB',
options: {
encrypt: false,
trustServerCertificate: true,
instanceName: 'SQLEXPRESS',
}
});
pool.connect().then(() => {
console.log('Connected to SQL Server');
app.get('/api/data', async (req, res) => {
try {
const result = await pool.request().query('SELECT * FROM Friends');
res.json(result.recordset); // Sends the data to the frontend
} catch (err) {
console.error('Query failed: ', err);
res.status(500).send('Server error');
}
});
}).catch(err => {
console.error('Database connection failed: ', err);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.post('/api/data', async (req, res) => {
try {
const { name, age, country } = req.body;
await pool.request()
.input('name', sql.VarChar, name)
.input('age', sql.Int, age)
.input('country', sql.VarChar, country)
.query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)');
res.status(201).send('Friend added successfully');
} catch (err) {
console.error('Insert query failed: ', err);
res.status(500).send('Server error');
}
});
app.put('/api/data/:id', async (req, res) => {
try {
const { id } = req.params;
const { name, age, country } = req.body;
await pool.request()
.input('id', sql.Int, id)
.input('name', sql.VarChar, name)
.input('age', sql.Int, age)
.input('country', sql.VarChar, country)
.query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id');
res.status(200).send('Friend updated successfully');
} catch (err) {
console.error('Update query failed: ', err);
res.status(500).send('Server error');
}
});
app.delete('/api/data/:id', async (req, res) => {
try {
const { id } = req.params;
await pool.request()
.input('id', sql.Int, id)
.query('DELETE FROM Friends WHERE id = @id');
res.status(200).send('Friend deleted successfully');
} catch (err) {
console.error('Delete query failed: ', err);
res.status(500).send('Server error');
}
});
</code>
<code>// backend/server.js const express = require('express'); const sql = require('mssql'); const app = express(); const PORT = 5000; const cors = require('cors'); app.use(cors()); app.use(express.json()); const pool = new sql.ConnectionPool({ user: 'sa', password: 'password', server: 'DESKTOP-OA96LT5', database: 'mydynamicDB', options: { encrypt: false, trustServerCertificate: true, instanceName: 'SQLEXPRESS', } }); pool.connect().then(() => { console.log('Connected to SQL Server'); app.get('/api/data', async (req, res) => { try { const result = await pool.request().query('SELECT * FROM Friends'); res.json(result.recordset); // Sends the data to the frontend } catch (err) { console.error('Query failed: ', err); res.status(500).send('Server error'); } }); }).catch(err => { console.error('Database connection failed: ', err); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); app.post('/api/data', async (req, res) => { try { const { name, age, country } = req.body; await pool.request() .input('name', sql.VarChar, name) .input('age', sql.Int, age) .input('country', sql.VarChar, country) .query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)'); res.status(201).send('Friend added successfully'); } catch (err) { console.error('Insert query failed: ', err); res.status(500).send('Server error'); } }); app.put('/api/data/:id', async (req, res) => { try { const { id } = req.params; const { name, age, country } = req.body; await pool.request() .input('id', sql.Int, id) .input('name', sql.VarChar, name) .input('age', sql.Int, age) .input('country', sql.VarChar, country) .query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id'); res.status(200).send('Friend updated successfully'); } catch (err) { console.error('Update query failed: ', err); res.status(500).send('Server error'); } }); app.delete('/api/data/:id', async (req, res) => { try { const { id } = req.params; await pool.request() .input('id', sql.Int, id) .query('DELETE FROM Friends WHERE id = @id'); res.status(200).send('Friend deleted successfully'); } catch (err) { console.error('Delete query failed: ', err); res.status(500).send('Server error'); } }); </code>
// backend/server.js

const express = require('express');
const sql = require('mssql');
const app = express();
const PORT = 5000;
const cors = require('cors');
app.use(cors());
app.use(express.json());



const pool = new sql.ConnectionPool({
  user: 'sa',
  password: 'password',
  server: 'DESKTOP-OA96LT5',
  database: 'mydynamicDB',
  options: {
    encrypt: false,
    trustServerCertificate: true,
    instanceName: 'SQLEXPRESS',
  }
});

pool.connect().then(() => {
  console.log('Connected to SQL Server');

  app.get('/api/data', async (req, res) => {
    try {
      const result = await pool.request().query('SELECT * FROM Friends');
      res.json(result.recordset);  // Sends the data to the frontend
    } catch (err) {
      console.error('Query failed: ', err);
      res.status(500).send('Server error');
    }
  });

}).catch(err => {
  console.error('Database connection failed: ', err);
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

app.post('/api/data', async (req, res) => {
    try {
      const { name, age, country } = req.body;
      await pool.request()
        .input('name', sql.VarChar, name)
        .input('age', sql.Int, age)
        .input('country', sql.VarChar, country)
        .query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)');
      res.status(201).send('Friend added successfully');
    } catch (err) {
      console.error('Insert query failed: ', err);
      res.status(500).send('Server error');
    }
  });
  app.put('/api/data/:id', async (req, res) => {
    try {
      const { id } = req.params;
      const { name, age, country } = req.body;
      await pool.request()
        .input('id', sql.Int, id)
        .input('name', sql.VarChar, name)
        .input('age', sql.Int, age)
        .input('country', sql.VarChar, country)
        .query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id');
      res.status(200).send('Friend updated successfully');
    } catch (err) {
      console.error('Update query failed: ', err);
      res.status(500).send('Server error');
    }
  });
  app.delete('/api/data/:id', async (req, res) => {
    try {
      const { id } = req.params;
      await pool.request()
        .input('id', sql.Int, id)
        .query('DELETE FROM Friends WHERE id = @id');
      res.status(200).send('Friend deleted successfully');
    } catch (err) {
      console.error('Delete query failed: ', err);
      res.status(500).send('Server error');
    }
  });

New contributor

Damipe Tiwo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

My web app returns a empty row in my table

I am building a dynamic editable table with MUI, react.js, node.js and SQL Server. When I visit my web app table, it shows an empty row. I’m new to this, please assist.

It shows me a blank page but it’s meant to display information from my database. Below are my three core files – please I’m confused at this point.

Here is my tablecomponent.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import {
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton,
TextField, Autocomplete
} from '@mui/material';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { useTable, usePagination, useFilters, useSortBy } from 'react-table';
import axios from 'axios'; // Make sure axios is imported
const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India'];
const TableComponent = ({ columns, data }) => {
const [editableRowIndex, setEditableRowIndex] = useState(null);
const [tableData, setTableData] = useState(data);
useEffect(() => {
console.log('tableData:', tableData); // Debug to see if tableData is correctly populated
setTableData(data);
}, [data]);
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
state: { pageIndex },
} = useTable(
{
columns,
data: tableData,
autoResetPage: false,
autoResetFilters: false,
},
useFilters,
useSortBy,
usePagination
);
// Handle edit and save
const handleEditClick = (rowIndex) => {
setEditableRowIndex(rowIndex);
};
const handleSaveClick = async () => {
const row = tableData[editableRowIndex]; // Get the row being edited
try {
// Update the database with the edited row data
await axios.put(`http://localhost:5000/api/data/${row.id}`, row);
// Update the tableData state with the new row data
const updatedData = tableData.map((item, index) => {
if (index === editableRowIndex) {
return row; // Replace the old row with the new updated row
}
return item; // Leave other rows unchanged
});
setTableData(updatedData); // Set the updated data
setEditableRowIndex(null); // Exit edit mode
} catch (error) {
console.error('Error updating data:', error);
}
};
const handleDeleteClick = async (rowIndex) => {
const row = tableData[rowIndex];
try {
await axios.delete(`http://localhost:5000/api/data/${row.id}`);
const updatedData = tableData.filter((_, index) => index !== rowIndex);
setTableData(updatedData);
} catch (error) {
console.error('Error deleting data:', error);
}
};
const handleCancelClick = () => {
setEditableRowIndex(null);
};
const handleCellChange = (e, rowIndex, columnId) => {
const value = e.target.value;
const updatedData = tableData.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnId]: value,
};
}
return row;
});
setTableData(updatedData);
};
const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => {
const updatedData = tableData.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnId]: newValue || '',
};
}
return row;
});
setTableData(updatedData);
};
return (
<TableContainer component={Paper}>
<Table {...getTableProps()} sx={{ minWidth: 650 }}>
<TableHead>
{headerGroups.map(headerGroup => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableCell {...column.getHeaderProps()}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}>
{column.render('Header')}
<span>
{column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</div>
{column.canFilter && (
<IconButton size="small">
<ArrowDropDownIcon />
{column.render('Filter')}
</IconButton>
)}
</div>
</TableCell>
))}
<TableCell>Actions</TableCell>
</TableRow>
))}
</TableHead>
<TableBody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => (
<TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}>
{editableRowIndex === i ? (
cell.column.id === 'country' ? (
<Autocomplete
options={countryOptions}
value={cell.value || ''}
onChange={(event, newValue) =>
handleAutocompleteChange(event, newValue, i, cell.column.id)
}
renderInput={(params) => (
<TextField {...params} variant="outlined" />
)}
/>
) : (
<TextField
value={cell.value}
onChange={(e) => handleCellChange(e, i, cell.column.id)}
variant="outlined"
/>
)
) : (
cell.render('Cell')
)}
</TableCell>
))}
<TableCell>
{editableRowIndex === i ? (
<>
<Button onClick={handleSaveClick}>Save</Button>
<Button onClick={handleCancelClick}>Cancel</Button>
</>
) : (
<>
<Button onClick={() => handleEditClick(i)}>Edit</Button>
<Button onClick={() => handleDeleteClick(i)}>Delete</Button>
</>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
<div style={{ marginTop: '10px' }}>
<Button onClick={previousPage} disabled={!canPreviousPage}>
Previous
</Button>
<span style={{ margin: '0 15px' }}>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<Button onClick={nextPage} disabled={!canNextPage}>
Next
</Button>
</div>
</TableContainer>
);
};
export default TableComponent;
</code>
<code>import React, { useState, useEffect } from 'react'; import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton, TextField, Autocomplete } from '@mui/material'; import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown'; import { useTable, usePagination, useFilters, useSortBy } from 'react-table'; import axios from 'axios'; // Make sure axios is imported const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India']; const TableComponent = ({ columns, data }) => { const [editableRowIndex, setEditableRowIndex] = useState(null); const [tableData, setTableData] = useState(data); useEffect(() => { console.log('tableData:', tableData); // Debug to see if tableData is correctly populated setTableData(data); }, [data]); const { getTableProps, getTableBodyProps, headerGroups, prepareRow, page, nextPage, previousPage, canNextPage, canPreviousPage, pageOptions, state: { pageIndex }, } = useTable( { columns, data: tableData, autoResetPage: false, autoResetFilters: false, }, useFilters, useSortBy, usePagination ); // Handle edit and save const handleEditClick = (rowIndex) => { setEditableRowIndex(rowIndex); }; const handleSaveClick = async () => { const row = tableData[editableRowIndex]; // Get the row being edited try { // Update the database with the edited row data await axios.put(`http://localhost:5000/api/data/${row.id}`, row); // Update the tableData state with the new row data const updatedData = tableData.map((item, index) => { if (index === editableRowIndex) { return row; // Replace the old row with the new updated row } return item; // Leave other rows unchanged }); setTableData(updatedData); // Set the updated data setEditableRowIndex(null); // Exit edit mode } catch (error) { console.error('Error updating data:', error); } }; const handleDeleteClick = async (rowIndex) => { const row = tableData[rowIndex]; try { await axios.delete(`http://localhost:5000/api/data/${row.id}`); const updatedData = tableData.filter((_, index) => index !== rowIndex); setTableData(updatedData); } catch (error) { console.error('Error deleting data:', error); } }; const handleCancelClick = () => { setEditableRowIndex(null); }; const handleCellChange = (e, rowIndex, columnId) => { const value = e.target.value; const updatedData = tableData.map((row, index) => { if (index === rowIndex) { return { ...row, [columnId]: value, }; } return row; }); setTableData(updatedData); }; const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => { const updatedData = tableData.map((row, index) => { if (index === rowIndex) { return { ...row, [columnId]: newValue || '', }; } return row; }); setTableData(updatedData); }; return ( <TableContainer component={Paper}> <Table {...getTableProps()} sx={{ minWidth: 650 }}> <TableHead> {headerGroups.map(headerGroup => ( <TableRow {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <TableCell {...column.getHeaderProps()}> <div style={{ display: 'flex', alignItems: 'center' }}> <div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}> {column.render('Header')} <span> {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''} </span> </div> {column.canFilter && ( <IconButton size="small"> <ArrowDropDownIcon /> {column.render('Filter')} </IconButton> )} </div> </TableCell> ))} <TableCell>Actions</TableCell> </TableRow> ))} </TableHead> <TableBody {...getTableBodyProps()}> {page.map((row, i) => { prepareRow(row); return ( <TableRow {...row.getRowProps()}> {row.cells.map(cell => ( <TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}> {editableRowIndex === i ? ( cell.column.id === 'country' ? ( <Autocomplete options={countryOptions} value={cell.value || ''} onChange={(event, newValue) => handleAutocompleteChange(event, newValue, i, cell.column.id) } renderInput={(params) => ( <TextField {...params} variant="outlined" /> )} /> ) : ( <TextField value={cell.value} onChange={(e) => handleCellChange(e, i, cell.column.id)} variant="outlined" /> ) ) : ( cell.render('Cell') )} </TableCell> ))} <TableCell> {editableRowIndex === i ? ( <> <Button onClick={handleSaveClick}>Save</Button> <Button onClick={handleCancelClick}>Cancel</Button> </> ) : ( <> <Button onClick={() => handleEditClick(i)}>Edit</Button> <Button onClick={() => handleDeleteClick(i)}>Delete</Button> </> )} </TableCell> </TableRow> ); })} </TableBody> </Table> <div style={{ marginTop: '10px' }}> <Button onClick={previousPage} disabled={!canPreviousPage}> Previous </Button> <span style={{ margin: '0 15px' }}> Page{' '} <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </span> <Button onClick={nextPage} disabled={!canNextPage}> Next </Button> </div> </TableContainer> ); }; export default TableComponent; </code>
import React, { useState, useEffect } from 'react';
import {
  Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, IconButton,
  TextField, Autocomplete
} from '@mui/material';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import { useTable, usePagination, useFilters, useSortBy } from 'react-table';
import axios from 'axios'; // Make sure axios is imported

const countryOptions = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France', 'Australia', 'India'];

const TableComponent = ({ columns, data }) => {
  const [editableRowIndex, setEditableRowIndex] = useState(null);
  const [tableData, setTableData] = useState(data);

  useEffect(() => {
    console.log('tableData:', tableData); // Debug to see if tableData is correctly populated
    setTableData(data);
  }, [data]);
  
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page,
    nextPage,
    previousPage,
    canNextPage,
    canPreviousPage,
    pageOptions,
    state: { pageIndex },
  } = useTable(
    {
      columns,
      data: tableData,
      autoResetPage: false,
      autoResetFilters: false,
    },
    useFilters,
    useSortBy,
    usePagination
  );

  // Handle edit and save
  const handleEditClick = (rowIndex) => {
    setEditableRowIndex(rowIndex);
  };

  const handleSaveClick = async () => {
    const row = tableData[editableRowIndex]; // Get the row being edited
    try {
      // Update the database with the edited row data
      await axios.put(`http://localhost:5000/api/data/${row.id}`, row);
  
      // Update the tableData state with the new row data
      const updatedData = tableData.map((item, index) => {
        if (index === editableRowIndex) {
          return row; // Replace the old row with the new updated row
        }
        return item; // Leave other rows unchanged
      });
  
      setTableData(updatedData); // Set the updated data
      setEditableRowIndex(null); // Exit edit mode
  
    } catch (error) {
      console.error('Error updating data:', error);
    }
  };
  
  const handleDeleteClick = async (rowIndex) => {
    const row = tableData[rowIndex];
    try {
      await axios.delete(`http://localhost:5000/api/data/${row.id}`);
      const updatedData = tableData.filter((_, index) => index !== rowIndex);
      setTableData(updatedData);
    } catch (error) {
      console.error('Error deleting data:', error);
    }
  };

  const handleCancelClick = () => {
    setEditableRowIndex(null);
  };

  const handleCellChange = (e, rowIndex, columnId) => {
    const value = e.target.value;
    const updatedData = tableData.map((row, index) => {
      if (index === rowIndex) {
        return {
          ...row,
          [columnId]: value,
        };
      }
      return row;
    });
    setTableData(updatedData);
  };

  const handleAutocompleteChange = (event, newValue, rowIndex, columnId) => {
    const updatedData = tableData.map((row, index) => {
      if (index === rowIndex) {
        return {
          ...row,
          [columnId]: newValue || '',
        };
      }
      return row;
    });
    setTableData(updatedData);
  };

  return (
    <TableContainer component={Paper}>
      <Table {...getTableProps()} sx={{ minWidth: 650 }}>
        <TableHead>
          {headerGroups.map(headerGroup => (
            <TableRow {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <TableCell {...column.getHeaderProps()}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div {...column.getSortByToggleProps()} style={{ cursor: 'pointer' }}>
                      {column.render('Header')}
                      <span>
                        {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
                      </span>
                    </div>
                    {column.canFilter && (
                      <IconButton size="small">
                        <ArrowDropDownIcon />
                        {column.render('Filter')}
                      </IconButton>
                    )}
                  </div>
                </TableCell>
              ))}
              <TableCell>Actions</TableCell>
            </TableRow>
          ))}
        </TableHead>
        <TableBody {...getTableBodyProps()}>
          {page.map((row, i) => {
            prepareRow(row);
            return (
              <TableRow {...row.getRowProps()}>
                {row.cells.map(cell => (
                  <TableCell {...cell.getCellProps()} sx={{ '&:nth-of-type(odd)': { backgroundColor: '#f9f9f9' }, '&:hover': { backgroundColor: '#f1f1f1' } }}>
                    {editableRowIndex === i ? (
                      cell.column.id === 'country' ? (
                        <Autocomplete
                          options={countryOptions}
                          value={cell.value || ''}
                          onChange={(event, newValue) =>
                            handleAutocompleteChange(event, newValue, i, cell.column.id)
                          }
                          renderInput={(params) => (
                            <TextField {...params} variant="outlined" />
                          )}
                        />
                      ) : (
                        <TextField
                          value={cell.value}
                          onChange={(e) => handleCellChange(e, i, cell.column.id)}
                          variant="outlined"
                        />
                      )
                    ) : (
                      cell.render('Cell')
                    )}
                  </TableCell>
                ))}
                <TableCell>
                  {editableRowIndex === i ? (
                    <>
                      <Button onClick={handleSaveClick}>Save</Button>
                      <Button onClick={handleCancelClick}>Cancel</Button>
                    </>
                  ) : (
                    <>
                      <Button onClick={() => handleEditClick(i)}>Edit</Button>
                      <Button onClick={() => handleDeleteClick(i)}>Delete</Button>
                    </>
                  )}
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
      <div style={{ marginTop: '10px' }}>
        <Button onClick={previousPage} disabled={!canPreviousPage}>
          Previous
        </Button>
        <span style={{ margin: '0 15px' }}>
          Page{' '}
          <strong>
            {pageIndex + 1} of {pageOptions.length}
          </strong>{' '}
        </span>
        <Button onClick={nextPage} disabled={!canNextPage}>
          Next
        </Button>
      </div>
    </TableContainer>
  );
};  

export default TableComponent; 

Here is my

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import TableComponent from './TableComponent';
import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined
import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined
import axios from 'axios';
const columns = [
{
Header: 'Name',
accessor: 'name',
Filter: DropdownTextFilter,
},
{
Header: 'Age',
accessor: 'age',
Filter: DropdownNumberFilter,
},
{
Header: 'Country',
accessor: 'country',
Filter: DropdownTextFilter,
},
];
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/api/data')
.then(response => {
console.log(response.data); // Check if data is fetched correctly
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div>
<h1>Custom Filter Table with Actions</h1>
<TableComponent columns={columns} data={data} />
</div>
);
}
export default App;
</code>
<code>import React, { useState, useEffect } from 'react'; import TableComponent from './TableComponent'; import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined import axios from 'axios'; const columns = [ { Header: 'Name', accessor: 'name', Filter: DropdownTextFilter, }, { Header: 'Age', accessor: 'age', Filter: DropdownNumberFilter, }, { Header: 'Country', accessor: 'country', Filter: DropdownTextFilter, }, ]; function App() { const [data, setData] = useState([]); useEffect(() => { axios.get('http://localhost:5000/api/data') .then(response => { console.log(response.data); // Check if data is fetched correctly setData(response.data); }) .catch(error => { console.error('Error fetching data:', error); }); }, []); return ( <div> <h1>Custom Filter Table with Actions</h1> <TableComponent columns={columns} data={data} /> </div> ); } export default App; </code>
import React, { useState, useEffect } from 'react';
import TableComponent from './TableComponent';
import DropdownNumberFilter from './DropdownNumberFilter'; // Make sure you have this filter defined
import DropdownTextFilter from './DropdownTextFilter'; // Make sure you have this filter defined
import axios from 'axios';

const columns = [
  {
    Header: 'Name',
    accessor: 'name',
    Filter: DropdownTextFilter,
  },
  {
    Header: 'Age',
    accessor: 'age',
    Filter: DropdownNumberFilter,
  },
  {
    Header: 'Country',
    accessor: 'country',
    Filter: DropdownTextFilter,
  },
];

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:5000/api/data')
      .then(response => {
        console.log(response.data); // Check if data is fetched correctly
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>Custom Filter Table with Actions</h1>
      <TableComponent columns={columns} data={data} />
    </div>
  );
}

export default App;

Here is my serve.js file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// backend/server.js
const express = require('express');
const sql = require('mssql');
const app = express();
const PORT = 5000;
const cors = require('cors');
app.use(cors());
app.use(express.json());
const pool = new sql.ConnectionPool({
user: 'sa',
password: 'password',
server: 'DESKTOP-OA96LT5',
database: 'mydynamicDB',
options: {
encrypt: false,
trustServerCertificate: true,
instanceName: 'SQLEXPRESS',
}
});
pool.connect().then(() => {
console.log('Connected to SQL Server');
app.get('/api/data', async (req, res) => {
try {
const result = await pool.request().query('SELECT * FROM Friends');
res.json(result.recordset); // Sends the data to the frontend
} catch (err) {
console.error('Query failed: ', err);
res.status(500).send('Server error');
}
});
}).catch(err => {
console.error('Database connection failed: ', err);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.post('/api/data', async (req, res) => {
try {
const { name, age, country } = req.body;
await pool.request()
.input('name', sql.VarChar, name)
.input('age', sql.Int, age)
.input('country', sql.VarChar, country)
.query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)');
res.status(201).send('Friend added successfully');
} catch (err) {
console.error('Insert query failed: ', err);
res.status(500).send('Server error');
}
});
app.put('/api/data/:id', async (req, res) => {
try {
const { id } = req.params;
const { name, age, country } = req.body;
await pool.request()
.input('id', sql.Int, id)
.input('name', sql.VarChar, name)
.input('age', sql.Int, age)
.input('country', sql.VarChar, country)
.query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id');
res.status(200).send('Friend updated successfully');
} catch (err) {
console.error('Update query failed: ', err);
res.status(500).send('Server error');
}
});
app.delete('/api/data/:id', async (req, res) => {
try {
const { id } = req.params;
await pool.request()
.input('id', sql.Int, id)
.query('DELETE FROM Friends WHERE id = @id');
res.status(200).send('Friend deleted successfully');
} catch (err) {
console.error('Delete query failed: ', err);
res.status(500).send('Server error');
}
});
</code>
<code>// backend/server.js const express = require('express'); const sql = require('mssql'); const app = express(); const PORT = 5000; const cors = require('cors'); app.use(cors()); app.use(express.json()); const pool = new sql.ConnectionPool({ user: 'sa', password: 'password', server: 'DESKTOP-OA96LT5', database: 'mydynamicDB', options: { encrypt: false, trustServerCertificate: true, instanceName: 'SQLEXPRESS', } }); pool.connect().then(() => { console.log('Connected to SQL Server'); app.get('/api/data', async (req, res) => { try { const result = await pool.request().query('SELECT * FROM Friends'); res.json(result.recordset); // Sends the data to the frontend } catch (err) { console.error('Query failed: ', err); res.status(500).send('Server error'); } }); }).catch(err => { console.error('Database connection failed: ', err); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); app.post('/api/data', async (req, res) => { try { const { name, age, country } = req.body; await pool.request() .input('name', sql.VarChar, name) .input('age', sql.Int, age) .input('country', sql.VarChar, country) .query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)'); res.status(201).send('Friend added successfully'); } catch (err) { console.error('Insert query failed: ', err); res.status(500).send('Server error'); } }); app.put('/api/data/:id', async (req, res) => { try { const { id } = req.params; const { name, age, country } = req.body; await pool.request() .input('id', sql.Int, id) .input('name', sql.VarChar, name) .input('age', sql.Int, age) .input('country', sql.VarChar, country) .query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id'); res.status(200).send('Friend updated successfully'); } catch (err) { console.error('Update query failed: ', err); res.status(500).send('Server error'); } }); app.delete('/api/data/:id', async (req, res) => { try { const { id } = req.params; await pool.request() .input('id', sql.Int, id) .query('DELETE FROM Friends WHERE id = @id'); res.status(200).send('Friend deleted successfully'); } catch (err) { console.error('Delete query failed: ', err); res.status(500).send('Server error'); } }); </code>
// backend/server.js

const express = require('express');
const sql = require('mssql');
const app = express();
const PORT = 5000;
const cors = require('cors');
app.use(cors());
app.use(express.json());



const pool = new sql.ConnectionPool({
  user: 'sa',
  password: 'password',
  server: 'DESKTOP-OA96LT5',
  database: 'mydynamicDB',
  options: {
    encrypt: false,
    trustServerCertificate: true,
    instanceName: 'SQLEXPRESS',
  }
});

pool.connect().then(() => {
  console.log('Connected to SQL Server');

  app.get('/api/data', async (req, res) => {
    try {
      const result = await pool.request().query('SELECT * FROM Friends');
      res.json(result.recordset);  // Sends the data to the frontend
    } catch (err) {
      console.error('Query failed: ', err);
      res.status(500).send('Server error');
    }
  });

}).catch(err => {
  console.error('Database connection failed: ', err);
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

app.post('/api/data', async (req, res) => {
    try {
      const { name, age, country } = req.body;
      await pool.request()
        .input('name', sql.VarChar, name)
        .input('age', sql.Int, age)
        .input('country', sql.VarChar, country)
        .query('INSERT INTO Friends (name, age, country) VALUES (@name, @age, @country)');
      res.status(201).send('Friend added successfully');
    } catch (err) {
      console.error('Insert query failed: ', err);
      res.status(500).send('Server error');
    }
  });
  app.put('/api/data/:id', async (req, res) => {
    try {
      const { id } = req.params;
      const { name, age, country } = req.body;
      await pool.request()
        .input('id', sql.Int, id)
        .input('name', sql.VarChar, name)
        .input('age', sql.Int, age)
        .input('country', sql.VarChar, country)
        .query('UPDATE Friends SET name = @name, age = @age, country = @country WHERE id = @id');
      res.status(200).send('Friend updated successfully');
    } catch (err) {
      console.error('Update query failed: ', err);
      res.status(500).send('Server error');
    }
  });
  app.delete('/api/data/:id', async (req, res) => {
    try {
      const { id } = req.params;
      await pool.request()
        .input('id', sql.Int, id)
        .query('DELETE FROM Friends WHERE id = @id');
      res.status(200).send('Friend deleted successfully');
    } catch (err) {
      console.error('Delete query failed: ', err);
      res.status(500).send('Server error');
    }
  });

New contributor

Damipe Tiwo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật