Delete Record API Interaction

When designing React components that interact with APIs, such as a "delete record" API, it’s important to consider how state management affects the performance and behavior of your application.

Considerations

Example Code

function deleteRecord(id) {
    // Optimistically remove the record from UI
    updateRecords((currentRecords) => currentRecords.filter(record => record.id !== id));
    fetch('/api/records/' + id, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) {
                // Handle failure: inform user and rollback UI changes
                alert('Failed to delete the record.');
                rollbackChanges(id);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            rollbackChanges(id);
        });
}

function rollbackChanges(id) {
    // Rollback UI changes if necessary
}
    

Static Demo

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">
  function App() {
      const initialRecords = [
          { id: 1, name: 'Record 1' },
          { id: 2, name: 'Record 2' },
          { id: 3, name: 'Record 3' }
      ];
      const [records, setRecords] = React.useState(initialRecords);

      const deleteRecord = (id) => {
          const newRecords = records.filter(record => record.id !== id);
          setRecords(newRecords);

          simulateDeleteAPI(id).then(response => {
              console.log('Delete successful:', response);
          }).catch(error => {
              console.error('Delete failed, re-inserting:', error);
              setRecords(currentRecords => [...currentRecords, initialRecords.find(record => record.id === id)]);
          });
      };

      const simulateDeleteAPI = (id) => {
          return new Promise((resolve, reject) => {
              setTimeout(() => {
                  if (id === 2) {
                      reject('Failed to delete due to server error.');
                  } else {
                      resolve('Deleted successfully.');
                  }
              }, 1000);
          });
      };

      return (
          <div className="container">
              <h1>Delete Record API Interaction</h1>
              <ul>
                  {records.map(record => (
                      <li key={record.id}>
                          {record.name} <button onClick={() => deleteRecord(record.id)}>Delete</button>
                      </li>
                  ))}
              </ul>
          </div>
      );
  }

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

Loading...