Building a React App with a Dummy API

In this tutorial, we will build a simple React app that manages a list of records. We will also simulate an API to handle fetching and deleting records.

Below, you can see the implementation of the React app along with the dummy API simulation.

React Code

<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<script type="text/babel">
  const { useState, useEffect } = React;

  // Dummy API simulation
  const dummyRecords = [
    { id: 1, name: 'Record 1' },
    { id: 2, name: 'Record 2' },
    { id: 3, name: 'Record 3' },
  ];

  const fetchRecords = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(dummyRecords);
      }, 500); // Simulate API delay
    });
  };

  const deleteRecord = (recordId) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const index = dummyRecords.findIndex(record => record.id === recordId);
        if (index !== -1) {
          dummyRecords.splice(index, 1);
          resolve({ success: true });
        } else {
          reject({ success: false });
        }
      }, 500); // Simulate API delay
    });
  };

  // React component
  const RecordsComponent = () => {
    const [records, setRecords] = useState([]);

    useEffect(() => {
      fetchRecords()
        .then(data => setRecords(data));
    }, []);

    const handleDelete = (recordId) => {
      setRecords(prevRecords => prevRecords.filter(record => record.id !== recordId));

      deleteRecord(recordId)
        .then(response => {
          if (!response.success) {
            throw new Error('Failed to delete the record');
          }
        })
        .catch(error => {
          console.error('Error:', error);
        });
    };

    return (
      <div>
        <h1>Demo Records</h1>
        <ul>
          {records.map(record => (
            <li key={record.id}>
              {record.name}
              <button onClick={() => handleDelete(record.id)}>Delete</button>
            </li>
          ))}
        </ul>
      </div>
    );
  };

  ReactDOM.render(<RecordsComponent />, document.getElementById('root'));
</script>