Skip to content

Instantly share code, notes, and snippets.

@marcovincit
Created July 29, 2020 23:12
Show Gist options
  • Select an option

  • Save marcovincit/085aa3f80b5f10be945d58b0e22982de to your computer and use it in GitHub Desktop.

Select an option

Save marcovincit/085aa3f80b5f10be945d58b0e22982de to your computer and use it in GitHub Desktop.

Revisions

  1. Marco Vincit created this gist Jul 29, 2020.
    55 changes: 55 additions & 0 deletions favorite-list-react.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    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>
    );
    }