-
-
Save bluengreen/bea46132053d1bd3c48e18e9293da3fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
import "./styles.css"; | |
const data = [ | |
{ id: 1, name: "Marco" }, | |
{ id: 2, name: "Lincoln" }, | |
{ id: 3, name: "Aya" } | |
]; | |
export default function App() { | |
const [favorites, setFavorites] = useState([]); | |
useEffect(() => { | |
setFavorites(data); | |
}, []); | |
useEffect(() => { | |
console.log(favorites); | |
}, [favorites]); | |
function handleFavorite(id) { | |
const newFavorites = favorites.map(item => { | |
return item.id === id ? { ...item, favorite: !item.favorite } : item; | |
}); | |
setFavorites(newFavorites); | |
} | |
return ( | |
<div className="App"> | |
<h1>Initial list</h1> | |
<ul> | |
{favorites.map((item, i) => ( | |
<li key={i}> | |
{item.name}{" "} | |
<button | |
onClick={() => { | |
handleFavorite(item.id); | |
}} | |
> | |
{item.favorite === true ? "Remove" : "Add"} | |
</button> | |
</li> | |
))} | |
</ul> | |
<h1>Favorite list</h1> | |
<ul> | |
{favorites.map(item => | |
item.favorite === true ? <li key={item.id}>{item.name}</li> : null | |
)} | |
</ul> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment