Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
4.4 kB
2
Indexable
Never
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import shareIcon from '../../images/shareIcon.svg'; // req33

interface RecipeType {
  strMeal: string;
  strDrink: string;
  strMealThumb: string;
  strDrinkThumb: string;
  strCategory: string;
  strAlcoholic: string;
  strInstructions: string;
  strYoutube: string;
}

function RecipeDetails(props: any) {
  const [mealsRecomendation, setMealsRecomendation] = useState();
  const [linkCopied, setLinkCopied] = useState(false); // req33

  useEffect(() => {
    fetch('https://www.themealdb.com/api/json/v1/1/search.php?s=')
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error('Erro ao buscar as refeições.');
      })
      .then((data) => {
        setMealsRecomendation(data.meals); // Atualiza o estado com os dados recebidos
      })
      .catch((error) => {
        console.error('.Erro ao buscar as refeições:', error);
      });
  }, []);
  console.log(mealsRecomendation);

  const [drinksRecomendations, setDrinksRecomendation] = useState();

  useEffect(() => {
    fetch('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=')
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error('Erro ao buscar as refeições');
      })
      .then((data) => {
        setDrinksRecomendation(data.drinks); // Atualiza o estado com os dados recebidos
      })
      .catch((error) => {
        console.error('Erro ao buscar as refeições:', error);
      });
  }, []);
  console.log(drinksRecomendations);

  const { tipo } = props;
  const { id } = useParams<string>();
  const path = tipo === 'meals' ? 'themealdb' : 'thecocktaildb';
  const [recipes, setRecipes] = useState<RecipeType[]>([]);

  const paragraphs = Array.from({ length: 20 }, (_, index) => index + 1);

  useEffect(() => {
    fetch(`https://www.${path}.com/api/json/v1/1/lookup.php?i=${id}`)
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error('Erro ao buscar as refeições');
      })
      .then((data) => {
        setRecipes(data.meals || data.drinks); // Atualiza o estado com os dados recebidos
      })
      .catch((error) => {
        console.error('Erro ao buscar as refeições:', error);
      });
  }, [id, path]);
  console.log(recipes);

  const handleShare = () => { // req33
    navigator.clipboard.writeText(window.location.href);
    setLinkCopied(true);
  };

  return (
    <div>
      {recipes && recipes.length > 0 ? (
        recipes.map((recipe, index) => (
          <div key={ index }>
            <h1 data-testid="recipe-title">{recipe.strMeal || recipe.strDrink}</h1>
            <img
              src={ tipo === 'meals'
                ? recipe.strMealThumb : recipe.strDrinkThumb }
              alt=""
              data-testid="recipe-photo"
            />
            <p data-testid="recipe-category">
              {recipe.strCategory}
              {recipe.strAlcoholic}
            </p>
            <div>
              {paragraphs.map((index1) => {
                const ingredientKey = `strIngredient${index1}` as keyof RecipeType;
                const measureKey = `strMeasure${index1}` as keyof RecipeType;

                return (
                  <p
                    key={ index1 }
                    data-testid={ `${index1 - 1}-ingredient-name-and-measure` }
                  >
                    {recipe[ingredientKey]}
                    <br />
                    {recipe[measureKey]}
                  </p>
                );
              })}
            </div>
            <p data-testid="instructions">{recipe.strInstructions}</p>
            <p data-testid="video">{recipe.strYoutube}</p>
          </div>
        ))
      ) : ''}

      <button
        data-testid="start-recipe-btn"
        style={ { position: 'fixed', bottom: 0 } }
      >
        Start Recipe
      </button>

      <button data-testid="start-recipe-btn">
        Continue Recipe
      </button>

      {/* req33 abaixo */}
      <button data-testid="share-btn" onClick={ handleShare }>
        <img src={ shareIcon } alt="Share" />
      </button>
      {linkCopied && <h3>Link copied!</h3>}

      <button data-testid="favorite-btn">
        Favorite
      </button>

    </div>
  );
}
export default RecipeDetails;