import { useState, useEffect } from "react"; import { Link, useLocation } from 'react-router-dom'; import { getRecipes } from "../services/frontendApi.js"; const RecipeBookTabs = () => { const location = useLocation(); const [lastViewedRecipeId, setLastViewedRecipeId] = useState(null); const loadRandomRecipeId = async () => { try { const recipes = await getRecipes(); if (recipes.length > 0) { const randomIndex = Math.floor(Math.random() * recipes.length); setLastViewedRecipeId(recipes[randomIndex].id); } } catch (error) { console.error('Error loading recipes:', error); } }; // update lastViewedRecipe id if we navigate to /recipe/${id} useEffect(() => { const match = /^\/recipe\/(\d+)$/.exec(location.pathname); if (match) { setLastViewedRecipeId(parseInt(match[1])); } }, [location.pathname, lastViewedRecipeId]); // choose random recipe on first load useEffect(() => { if (!lastViewedRecipeId) { loadRandomRecipeId(); } }, []); const tabs = [ { id: '/', label: 'Cookbook', icon: '📚' }, { id: `/recipe/${lastViewedRecipeId}`, label: 'Recipe', icon: '🥗' }, { id: '/add-recipe', label: 'Add', icon: '➕' }, { id: '/about', label: 'About', icon: '🍽️' }, ]; return (
{tabs.map((tab) => { const isActive = location.pathname === tab.id || (location.pathname.startsWith(tab.id) && tab.id === "/recipe/"); return (
{tab.icon} {tab.label}
{ isActive && ( <>
) } ); })}
); }; export default RecipeBookTabs;