How to I get a React list to update its items upon deletion with Next.JS server actions?
Unanswered
Dylan Wong posted this in #help-forum
How to I get a React list to update its items upon deletion?
So say I have a list, each with a button that says "Delete This", which will delete this item upon clicking it
I initialize the list items in React:
I call this function at the beginning to get the items:
Item deletion must involve server API:
The list is then updated:
The problem is that
So say I have a list, each with a button that says "Delete This", which will delete this item upon clicking it
I initialize the list items in React:
const [items, setItems] = useState([]);I call this function at the beginning to get the items:
useEffect(() => {
// Fetch your items from your API and set it.
fetch('/api/items').then(response => response.json()).then(data => setItems(data));
}, []);Item deletion must involve server API:
const deleteThis = async (itemId) => {
// Call your API to delete the item.
try {
await fetch(/api/items/${itemId}, { method: 'DELETE' });
// If successful, filter out the deleted item from the state.
setItems(prevItems => prevItems.filter(item => item.id !== itemId));
} catch (error) {
console.error("Failed to delete the item:", error);
}
}The list is then updated:
return (
<div>
{items.map(item => (
<div key={item.id}>
{item.name}
<button onClick={() => deleteThis(item.id)}>Delete</button>
</div>
))}
</div>
);The problem is that
await fetch(/api/items/${itemId}, { method: 'DELETE' }); is a server action but setItems(prevItems => prevItems.filter(item => item.id !== itemId)); is a client action, so I can't do both here. So that means I can't update the list. In that case what's the correct way to get Next.js to update a list upon item deletion?