Untitled
unknown
plain_text
2 years ago
3.4 kB
16
Indexable
import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import useStore from '../store/useStore';
const firstLetter = 'first-letter';
function SearchBar() {
const navigate = useNavigate();
const { pathname } = useLocation();
const setRecipes = useStore((state:any) => state.setRecipes);
const [searchTerm, setSearchTerm] = useState('');
const [searchType, setSearchType] = useState('ingredient');
const path = pathname.includes('meals') ? 'themealdb' : 'thecocktaildb';
const pageType = pathname.includes('meals') ? 'meals' : 'drinks';
const apiIngredients = `https://www.${path}.com/api/json/v1/1/filter.php?i=${searchTerm}`;
const apiName = `https://www.${path}.com/api/json/v1/1/search.php?s=${searchTerm}`;
const apiFirstLetter = `https://www.${path}.com/api/json/v1/1/search.php?f=${searchTerm}`;
let endpoint = '';
function fetchEndPoint() {
if (searchType === 'ingredient') {
endpoint = apiIngredients;
} else if (searchType === 'name') {
endpoint = apiName;
}
fetchAux();
}
const fetchTerm = () => {
if (searchType === firstLetter) {
if (searchTerm.length === 1) {
endpoint = apiFirstLetter;
} else {
(window.alert('Your search must have only 1 (one) character'));
}
}
};
const fetchAux = () => {
fetchTerm();
// esse fetch vai sair qunado aplicarmos o context API
fetch(endpoint)
.then((response) => response.json())
.then((data) => {
if (data[pageType].length === 1) {
const idType = pageType === 'meals' ? 'idMeal' : 'idDrink';
const id = data[pageType][0][idType];
navigate(`/${pageType}/${id}`);
console.log('perdidos', `/${pageType}/${id}`);
}
setRecipes(data);
})
.catch(() => {
window.alert("Sorry, we haven't found any recipes for these filters.");
});
};
return (
<div className="search-bar">
<input
type="text"
id="search-input"
data-testid="search-input"
value={ searchTerm }
onChange={ (e) => setSearchTerm(e.target.value) }
/>
<div className="search-options">
<label>
<input
type="radio"
name="search-type"
value="ingredient"
data-testid="ingredient-search-radio"
checked={ searchType === 'ingredient' }
onChange={ () => setSearchType('ingredient') }
/>
Buscar por Ingrediente
</label>
<label>
<input
type="radio"
name="search-type"
value="name"
data-testid="name-search-radio"
checked={ searchType === 'name' }
onChange={ () => setSearchType('name') }
/>
Buscar por Nome
</label>
<label>
<input
type="radio"
name="search-type"
value={ firstLetter }
data-testid="first-letter-search-radio"
checked={ searchType === firstLetter }
onChange={ () => setSearchType('first-letter') }
/>
Buscar pela Primeira Letra
</label>
</div>
<button
id="search-button"
data-testid="exec-search-btn"
onClick={ fetchEndPoint }
>
Buscar
</button>
</div>
);
}
export default SearchBar;
Editor is loading...