I'm making a recipe app. I want the user to be able to add recipes to a favorites list. There are 3 React components involved. Recipes, add to favorites and favorites.
The Recipe component displays various details about the selected recipe.
The AddToFavorites component is a button rendered in the Recipe component.
The Favorites component is a list that displays all items added to Favorites using the "Add to Favorites" button.
function Favorites() { const [favList, setFavList] = useState(localStorage.getItem('favorites')); return ({favList} {favList.map(listItem => { ) }{listItem} })}
function Recipe() { let params = useParams(); const [details, setDetails] = useState({}); const [activeTab, setActiveTab] = useState('summary'); const fetchDetails = async () => { const data = await fetch(`https://api.spoonacular.com/recipes/${params.name}/information?apiKey=${process.env.REACT_APP_API_KEY}`); const detailData = await data.json(); setDetails(detailData); } useEffect(() => { fetchDetails(); }, [params.name]); return () } {details.title}
{activeTab === 'instructions' && ( )} {activeTab === 'ingredients' && ({details.extendedIngredients && details.extendedIngredients.map((ingredient) => (
)} {activeTab === 'summary' && (- {ingredient.original}
))})}
function AddToFavorites(details) { const [active, setActive] = useState(false); const [favorites, setFavorites] = useState([]); const handleActive = () => { setActive(!active); }; const handleFavorites = () => { handleActive(); if(active){ removeFromFavorites(); } else if(!active) { addToFavorites(); } }; const addToFavorites = () => { handleActive(); setFavorites([...favorites, details]); console.log(favorites) localStorage.setItem('favorites', JSON.stringify(favorites)); }; return ({!active ? 'Add to favorites' : 'Remove from favorites'} ) }
What I've tried to do so far:
When I add an item to favorites, I can add one item or multiple times. But when I go to a new recipe and add another item, it deletes the old item and restarts.
I've been looking into it for a few days and trying different things but I can't figure it out.
This seems to be a good example of shared state. If yourFavoritesdata is managed in one place, you won't have synchronization issues when adding, deleting or displaying it.
I recommend creating a context
Then wrap the relevant parts of the application with a context provider, e.g.
Use context hookswhenever you need to read or modifyFavorites
You can also use any other form of state management, such as Redux.