Created
July 29, 2020 23:12
-
-
Save marcovincit/085aa3f80b5f10be945d58b0e22982de 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