Untitled

 avatar
unknown
plain_text
2 years ago
4.7 kB
3
Indexable
import { useEffect, useState } from 'react';
import clipboard from 'clipboard-copy';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import {
  Container,
  Header,
  HeaderTitle,
  IconButton,
  LogoHeader,
  WrapperButtons,
  WrapperIconsFavorite,
  WrapperHeaderTitle,
} from './styles';
import shareImg from '../../images/share.svg';
import likeImg from '../../images/like.svg';
import dessertImg from '../../images/dessert.svg';

const initialStateRecipe = {
  strMeal: '',
  strInstructions: '',
  strMealThumb: '',
};
export function RecipeInProgress() {
  const { id } = useParams();
  const [recipe, setRecipe] = useState(initialStateRecipe);
  const [infoRecipes, setInfoRecipes] = useState([]);
  const [clipShare, setClipShare] = useState(false);
  const copyLink = clipboard;
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [ingredients, setIngredients] = useState([]);

  function getRecipeById(idDaReceita) {
    const url = pathname.includes('meals') ? ('themealdb') : ('thecocktaildb');
    fetch(`https://www.${url}.com/api/json/v1/1/lookup.php?i=${idDaReceita}`)
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error('Erro ao buscar as refeições');
      })
      .then((data) => {
        const { meals, drinks } = data;
        // const { strMeal, strInstructions, strMealThumb } = meals[0];
        // setRecipe({ strMeal, strInstructions, strMealThumb });
        setInfoRecipes(Object.values(data)[0][0]);
        setIngredients(data);
      }).catch((error) => {
        console.error('Erro ao buscar as refeições:', error);
      });
  }
  useEffect(() => {
    getRecipeById(id);
  }, []);

  // const { strMeal, strInstructions, strMealThumb } = recipe;
  const clipBoardRecipe = async () => {
    await copyLink(`${protocol}//${host}/${infoRecipes.type}s/${idDaReceita}`);
    setClipShare(true);
  };
  const handleCheck = (ingredient) => {
    if (infoRecipes.includes(ingredient)) {
      setInfoRecipes(infoRecipes.filter((item) => item !== ingredient));
    } else {
      setInfoRecipes([...infoRecipes, ingredient]);
    }
  };

  const buttonFinish = () => {
    return infoRecipes.length === ingredients.length;
  };

  const finalizandoReceita = () => {
    const receitasFeitas = JSON.parse(localStorage.getItem('doneRecipes') || '[]');
    localStorage.setItem('doneRecipes', JSON.stringify([...receitasFeitas, infoRecipes]));
    localStorage.setItem('doneRecipes', JSON.stringify([infoRecipes]));
    navigate('/done-recipes');
  };

  const ingredientsKeys = Object.keys(infoRecipes)
    .filter((key) => key.includes('strIngredient') && infoRecipes[key] !== '');

  return (
    <Container>
      <Header imgSrc={ infoRecipes.strMealThumb || infoRecipes.strDrinkThumb }>
        <WrapperIconsFavorite>
          <LogoHeader src={ dessertImg } />
          <WrapperButtons>
            <IconButton imgSrc={ shareImg } />
            <IconButton data-testid="favorite-btn" imgSrc={ likeImg } />
          </WrapperButtons>
        </WrapperIconsFavorite>
        <WrapperHeaderTitle>
          <HeaderTitle>{infoRecipes.strMeal || infoRecipes.strDrink}</HeaderTitle>
        </WrapperHeaderTitle>
      </Header>
      <h1 data-testid="recipe-title">{infoRecipes.strMeal || infoRecipes.strDrink}</h1>
      <img
        alt="imagem"
        src={ infoRecipes.strMealThumb || infoRecipes.strDrinkThumb }
        data-testid="recipe-photo"
      />
      <h3 data-testid="recipe-category">{infoRecipes.strCategory}</h3>
      <h3 data-testid="recipe-category">{infoRecipes.strAlcoholic}</h3>
      {ingredientsKeys.map((ingredient, index) => (
        <div key={ index } data-testid={ `${index}-ingredient-name-and-measure` }>
          <label
            data-testid={ `${index}-ingredient-step` }
            // className={ infoRecipes.includes(ingredient) ? 'checked' : '' }
          >
            {/* <input
              type="checkbox"
              // checked={ infoRecipes.includes(ingredient) }
              onChange={ () => handleCheck(ingredient) }
            /> */}
            {infoRecipes[ingredient]}
          </label>
        </div>
      ))}
      <h2>Instructions</h2>
      <p data-testid="instructions">{infoRecipes.strInstructions}</p>

      <button
        onClick={ finalizandoReceita }
        data-testid="finish-recipe-btn"
        disabled={ !buttonFinish() }
      >
        Finalizar receita
      </button>
      <button onClick={ () => clipBoardRecipe() }>
        {clipShare && <p>Link copiado!</p>}
        <img src={ shareImg } alt="share" data-testid="share-btn" />
      </button>

    </Container>
  );
}
Editor is loading...