Ejercicio mostrar Posts

App

import React, { useState, useEffect } from "react";
import Post from "./Post";
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
    const [data, setData] = useState(null);
  
    useEffect(() => {
      fetch("https://jsonplaceholder.typicode.com/posts")
        .then((response) => response.json())
        .then((json) => setData(json));
  
      return () => {
        console.log("Limpieza de efecto (si aplica)");
      };
    }, []); // Solo se ejecuta una vez, al montar el componente.
    const removePost=(id)=>{
        setData(data.filter(post=>post.id!=id))
    }
    return (
      <div>
        {data ? <table class="table table-striped">
        <thead>
          <tr>
            <th>Id</th>
            <th>Title</th>
            <th>Body</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
            {data.map((post)=>
               
                <Post key={post.id} post={post} remove={removePost}/>
               )}
        </tbody>
        </table>
        : <button class="btn btn-primary">
        <span class="spinner-border spinner-border-sm"></span>
        Cargando...
      </button>}
      </div>
    );
  }
  
  export default App;

Post

const Post= ({post,remove}) => {
    return <tr>
        <td>{post.id}</td>
        <td>{post.title}</td>
        <td>{post.body.slice(0,20)}...</td>
        <td><button class="btn btn-danger" onClick={()=>{remove(post.id)}}>Borrar</button></td>
    </tr>
}

export default Post;

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos