Untitled

 avatar
unknown
plain_text
2 years ago
2.7 kB
5
Indexable
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import useStore from '../../store/useStore';

interface Props {
  tipo: string;
}
function Recipes(props: Props) {
  const { tipo } = props;
  const meals = useStore((state: any) => state.meals);
  const drinks = useStore((state: any) => state.drinks);
  const recipes = useStore((state: any) => state.recipes);
  const setRecipes = useStore((state:any) => state.setRecipes);
  
   const { pathname } = useLocation();
  const [category, setCategory] = useState({
    meals: [],
    drinks: [],
  });

  const path = pathname.includes('meals') ? 'themealdb' : 'thecocktaildb';
  const recipeType = pathname.includes('meals') ? 'meals' : 'drinks';

  useEffect(() => {
    fetch(`https://www.${path}.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) => {
        setRecipes(data); // Atualiza o estado com os dados recebidos
      })
      .catch((error) => {
        console.error('Erro ao buscar as refeições:', error);
      });
  }, []);
  
  useEffect(() => {
    fetch(`https://www.${path}.com/api/json/v1/1/list.php?c=list`)
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error('Erro ao buscar as refeições');
      })
      .then((data) => {
        setCategory(data); // Atualiza o estado com os dados recebidos
      })
      .catch((error) => {
        console.error('Erro ao buscar as refeições:', error);
      });
  }, []);

  const renderRecipes = recipes[recipeType].slice(0, 12);

  return (
    <>
      <p>RECEITAS</p>

      { category[recipeType].slice(0, 5).map((categoria, index) => (
        <div key={ index }>
          <button
            data-testid={ `${categoria.strCategory}-category-filter` }
          >
            {`${categoria.strCategory}`}

          </button>
        </div>
      ))}

      {
      renderRecipes.map((recipe: any, index: any) => {
          return (
            <div key={ index } data-testid={ `${index}-recipe-card` }>
              <h2
                data-testid={ `${index}-card-name` }
              >
                {recipe.strMeal || recipe.strDrink}
              </h2>
              <img
                src={ recipe.strMealThumb || recipe.strDrinkThumb }
                data-testid={ `${index}-card-img` }
                alt="recipeImg"
              />
            </div>
          );
        })
      }
      </>
  );
}
export default Recipes;
Editor is loading...