javascript – How to get data form backend [MERN]

I am having trouble retrieving values ​​from backend as data variable as in below code and I have code that I wrote in Code2. I want to retrieve data from backend as data variable from code1.

Code1

import React, { useRef, useState } from "react";
import "antd/dist/antd.css";

import { SearchOutlined } from "@ant-design/icons";
import { Button, Input, Space, Table } from "antd";

import Highlighter from "react-highlight-words";
const data = [
  {
    key: "1",
    name: "John Brown",
    age: 32,
    address: "New York No. 1 Lake Park",
  },
  {
    key: "2",
    name: "Joe Black",
    age: 42,
    address: "London No. 1 Lake Park",
  },
  {
    key: "3",
    name: "Jim Green",
    age: 32,
    address: "Sidney No. 1 Lake Park",
  },
  {
    key: "4",
    name: "Jim Red",
    age: 32,
    address: "London No. 2 Lake Park",
  },
];

const TableInven = () => {
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const searchInput = useRef(null);

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div
        style={{
          padding: 8,
        }}
      >
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: "block",
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            Search
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? "#1890ff" : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: "#ffc069",
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      width: "30%",
      ...getColumnSearchProps("name"),
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
      width: "20%",
      ...getColumnSearchProps("age"),
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
      ...getColumnSearchProps("address"),
      sorter: (a, b) => a.address.length - b.address.length,
      sortDirections: ["descend", "ascend"],
    },
  ];
  return <Table columns={columns} dataSource={data} />;
};

export default TableInven;

Code(2) How to push code on ListInven variable to data variable on code(1)

export const InvenListResults = ({ props, ...rest }) => {
  const [ListInven, setListInven] = useState([]);
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [searchTerm, setsearchTerm] = useState("");
  const [ProJect, setProJect] = useState("");
  const [ValueSelect, setValueSelect] = useState("");

  const SelectProjects = (val) => {
    Axios.get(`http://localhost:3001/${val}`)
      .then((response) => {
        setListInven(response.data);
      })
      .catch(() => {
        console.log("err");
      });
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  const handlePageChange = (event, newPage) => {
    setPage(newPage);
  };
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <Card {...rest}>
      <Box sx={{ mt: 1 }}>
        <Card>
          <CardContent>
            <SelectSmall getValue={SelectProjects} />

            <Box sx={{ maxWidth: 500 }}>
              <TextField
                fullWidth
                placeholder="Search Inventory"
                variant="outlined"
                onChange={(event) => {
                  setsearchTerm(event.target.value);
                }}
              />
            </Box>
          </CardContent>
        </Card>
      </Box>
      <PerfectScrollbar>
        <Box sx={{ minWidth: 1050 }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Branch</TableCell>
                <TableCell>HostName</TableCell>
                <TableCell>PartNumber</TableCell>
                <TableCell>Serial</TableCell>
                <TableCell>Stack</TableCell>
                <TableCell>IP Address</TableCell>
                <TableCell>Location</TableCell>
                <TableCell>Room</TableCell>
                <TableCell>Priority</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {ListInven.filter((val) => {
                if (searchTerm === "") {
                  return val;
                } else if (
                  val.HostName?.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Room?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  val.Location?.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.PartNumber.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Priority.toLowerCase().includes(
                    searchTerm.toLowerCase()
                  ) ||
                  val.Branch.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  val.Serial1?.toLowerCase().includes(searchTerm.toLowerCase())
                ) {
                  return val;
                }
              })
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((val, index) => (
                  <TableRow>
                    <TableCell>{val.Branch}</TableCell>
                    <TableCell>{val.HostName}</TableCell>
                    <TableCell>{val.PartNumber}</TableCell>
                    <TableCell>{val.Serial1}</TableCell>
                    <TableCell>{val.Stack}</TableCell>
                    <TableCell>{val.ipAddress}</TableCell>
                    <TableCell>{val.Location}</TableCell>
                    <TableCell>{val.Room}</TableCell>
                    <TableCell>
                      <SeverityPill
                        color={
                          (val.Priority === "Low" && "success") ||
                          (val.Priority === "High" && "error") ||
                          (val.Priority === "Very High" && "error") ||
                          "warning"
                        }
                      >
                        {val.Priority}
                      </SeverityPill>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </Box>
      </PerfectScrollbar>
      <TablePagination
        component="div"
        count={ListInven.length}
        onPageChange={handlePageChange}
        onRowsPerPageChange={handleChangeRowsPerPage}
        page={page}
        rowsPerPage={rowsPerPage}
        rowsPerPageOptions={[5, 10, 25]}
      />
    </Card>
  );
};

Anyone please help me

Leave a Comment