Deleting Memories

By now you are starting to feel the rhythm of remote state management: add a thunk creator to send a request to the web service, dispatch an action to synchronize the global store, handle the action in the reducer, and wire up the interface to dispatch the thunk. Deleting a memory follows this same pattern. You start with a thunk that hits the DELETE endpoint of your web service:

export function deleteMemory(id) {
return dispatch => {
const options = {
method: 'DELETE',
};
fetch(`https://example.com:8443/memories/${id}`, options)
.then(assertResponse)
.then(response => response.json())
.then(data => {
if (data.ok) {
dispatch(removeMemory(id));
}
});
};
}

The endpoint expects the ID as a URL component. No payload is sent in the request body.

You need an action to remove the deleted memory from the global store, so you add an enum instance and an action creator:

export const Action = Object.freeze({
// ...
RemoveMemory: 'RemoveMemory',
});

export function removeMemory(id) {
return {type: Action.RemoveMemory, payload: id};
}

In the reducer, you add a case to cull the removed memory. The Array.filter method is a good tool for this job:

function reducer(state, action) {
switch (action.type) {
// ...
case Action.RemoveMemory:
return {
...state,
memories: state.memories.filter(memory => memory.id !== action.payload),
};
// ...
}
}

Finally you respond to clicks on the delete button in the Memory component by dispatching the delete thunk:

// ...
import {
startMemoryEdit,
cancelMemoryEdit,
saveMemoryEdit,
deleteMemory,
} from './actions';

export function Memory(memory) {
// ...

if (memory.isEditing) {
return (
// ...
<button
onClick={() => dispatch(deleteMemory(memory.id))}
>Delete</button>
// ...
);
} else {
// ...
}
}

Try deleting a memory. Does it go away? When your reload the app, is it still gone? Recall that when you set up your web service, you implemented soft-deletes. The memory is still in the database, but it the web service filters out any soft-deleted memories in its SELECT statement.