[Local simulation echo data] React+AntD+Typescript

When using React 18, Ant Design 5, and TypeScript, you have several ways to implement data echoing when opening an Edit modal or performing a Delete operation while simulating data locally. Here are two common implementations:

1. Use useState and useEffect hooks

import React, {<!-- --> useState, useEffect } from 'react';
import {<!-- --> Table, Modal, Button } from 'antd';

const CustomTable: React.FC = () => {<!-- -->
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<any>(null);

  useEffect(() => {<!-- -->
    // Simulate loading data from local JSON file
    const fetchData = async () => {<!-- -->
      const response = await fetch('/path/to/data.json');
      const data = await response.json();
      setDataSource(data);
    };
    fetchData();
  }, []);

  const handleDelete = () => {<!-- -->
    const newData = dataSource.filter((item) => !selectedRowKeys.includes(item.key));
    setDataSource(newData);
    setSelectedRowKeys([]);
  };

  const handleEdit = (record: any) => {<!-- -->
    setSelectedRecord(record);
    setIsModalVisible(true);
  };

  const handleModalOk = (values: any) => {<!-- -->
    const newData = dataSource.map((item) => {<!-- -->
      if (item.key === selectedRecord.key) {<!-- -->
        return {<!-- --> ...item, ...values };
      }
      return item;
    });
    setDataSource(newData);
    setIsModalVisible(false);
  };

  const handleModalCancel = () => {<!-- -->
    setIsModalVisible(false);
  };

  const columns = [
    {<!-- -->
      title: 'Name',
      dataIndex: 'name',
    },
    {<!-- -->
      title: 'Age',
      dataIndex: 'age',
    },
    {<!-- -->
      title: 'Address',
      dataIndex: 'address',
    },
    {<!-- -->
      title: 'Actions',
      dataIndex: 'actions',
      render: (_, record) => (
        <>
          <Button type="link" onClick={<!-- -->() => handleEdit(record)}>
            Edit
          </Button>
          <Button type="link" danger onClick={<!-- -->() => handleDelete()}>
            Delete
          </Button>
        </>
      ),
    },
  ];

  const rowSelection = {<!-- -->
    selectedRowKeys,
    onChange: (keys: string[]) => {<!-- -->
      setSelectedRowKeys(keys);
    },
  };

  return (
    <>
      <Table dataSource={<!-- -->dataSource} columns={<!-- -->columns} rowSelection={<!-- -->rowSelection} />
      <Modal
        title="Edit Record"
        visible={<!-- -->isModalVisible}
        onOk={<!-- -->handleModalOk}
        onCancel={<!-- -->handleModalCancel}
        destroyOnClose
      >
        <p>Name: {<!-- -->selectedRecord?.name}</p>
        <p>Age: {<!-- -->selectedRecord?.age}</p>
        <p>Address: {<!-- -->selectedRecord?.address}</p>
      </Modal>
    </>
  );
};

export default CustomTable;

In this method, we use the useState and useEffect hooks to handle the loading and updating of data. In the useEffect hook, we simulate loading data from a local JSON file and use the setDataSource function to store the data in the dataSource state. When the user clicks the “Edit” button, we store the selected record in the selectedRecord state and set the isModalVisible state to true to Open the edit modal. In the modal box, we display the details of the selected records and allow the user to edit them. When the user clicks the “OK” button, we update the dataSource state to reflect the user’s changes and set the isModalVisible state to false to turn off the mod status box.

2. Use Mock database

If you want more flexibility in managing mock data and sharing it across your application, you may consider using a mock database library such as json-server. The following is sample code using json-server:

First, you need to install json-server and json-server-auth (for mock authentication):

npm install -g json-server json-server-auth

Then, create a db.json file containing your simulation data:

{<!-- -->
  "users": [
    {<!-- -->
      "id": 1,
      "name": "John Doe",
      "email": "[email protected]"
    },
    {<!-- -->
      "id": 2,
      "name": "Jane Smith",
      "email": "[email protected]"
    }
  ]
}

Next, create a server.js file to start json-server:

const jsonServer = require('json-server');
const auth = require('json-server-auth');

const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.db = router.db;
server.use(middlewares);
server.use(auth);
server.use(router);
server.listen(3000, () => {<!-- -->
  console.log('JSON Server is running');
});

Run the following command to start json-server:

node server.js

You can now access the simulated user data via http://localhost:3000/users.

In your React application, you can use libraries such as axios or fetch to get and update mock data. Here is a sample code:

import React, {<!-- --> useState, useEffect } from 'react';
import axios from 'axios';
import {<!-- --> Table, Modal, Button } from 'antd';

const CustomTable: React.FC = () => {<!-- -->
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<any>(null);

  useEffect(() => {<!-- -->
    const fetchData = async () => {<!-- -->
      const response = await axios.get('http://localhost:3000/users');
      setDataSource(response.data);
    };
    fetchData();
  }, []);

  const handleDelete = async () => {<!-- -->
    await axios.delete(`http://localhost:3000/users/${<!-- -->selectedRecord.id}`);
    const newData = dataSource.filter((item) => item.id !== selectedRecord.id);
    setDataSource(newData);
    setSelectedRowKeys([]);
  };

  const handleEdit = (record: any) => {<!-- -->
    setSelectedRecord(record);
    setIsModalVisible(true);
  };

  const handleModalOk = async (values: any) => {<!-- -->
    await axios.patch(`http://localhost:3000/users/${<!-- -->selectedRecord.id}`, values);
    const newData = dataSource.map((item) => {<!-- -->
      if (item.id === selectedRecord.id) {<!-- -->
        return {<!-- --> ...item, ...values };
      }
      return item;
    });
    setDataSource(newData);
    setIsModalVisible(false);
  };

  const handleModalCancel = () => {<!-- -->
    setIsModalVisible(false);
  };

  const columns = [
    {<!-- -->
      title: 'Name',
      dataIndex: 'name',
    },
    {<!-- -->
      title: 'Email',
      dataIndex: 'email',
    },
    {<!-- -->
      title: 'Actions',
      dataIndex: 'actions',
      render: (_, record) => (
        <>
          <Button type="link" onClick={<!-- -->() => handleEdit(record)}>
            Edit
          </Button>
          <Button type="link" danger onClick={<!-- -->() => handleDelete()}>
            Delete
          </Button>
        </>
      ),
    },
  ];

  const rowSelection = {<!-- -->
    selectedRowKeys,
    onChange: (keys: string[]) => {<!-- -->
      setSelectedRowKeys(keys);
    },
  };

  return (
    <>
      <Table dataSource={<!-- -->dataSource} columns={<!-- -->columns} rowSelection={<!-- -->rowSelection} />
      <Modal
        title="Edit Record"
        visible={<!-- -->isModalVisible}
        onOk={<!-- -->handleModalOk}
        onCancel={<!-- -->handleModalCancel}
        destroyOnClose
      >
        <p>Name: {<!-- -->selectedRecord?.name}</p>
        <p>Email: {<!-- -->selectedRecord?.email}</p>
      </Modal>
    </>
  );
};

export default CustomTable;

In this approach, we use the axios library to send HTTP requests and communicate with json-server. In the useEffect hook, we use the axios.get method to get data from json-server and the setDataSource function Store data in dataSource state. When the user clicks the “Edit” button, we store the selected record in the selectedRecord state and set the isModalVisible state to true to Open