Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.1 kB
1
Indexable
Never
import {useEffect, useState} from 'react';

import "./App.css";
import TodoItem from './component/toDoItem';

function App() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch('/todos')
      .then(res => res.json())
      .then(data => { setItems([...data])
   })
 }, [])

 const onDeleteItem = (id) => {
  fetch(`/todos/${id}/delete`, {
    method: 'POST'
  })
  .then((response) => {
   if (response.ok) {
     setItems(items.filter(item => item.id !== id));
   } else {
     throw new Error('Error deleting item');
   }
 })
 .catch((error) => {
   console.error('Error:', error);
 });

 }

 const toDoItemComponentsArr = items.map((item) => {
  return <TodoItem key={item.id} task={item.task} onDelete={onDeleteItem}/>
})


return (
  <div className="App">
    <ul>
      {toDoItemComponentsArr}
    </ul>
  </div>
);
}

export default App;


const TodoItem = (props) => {
  console.log(props)
  return (<li>{props.task} <button onClick={props.onDelete}>Delete</button></li>);
};

export default TodoItem;