Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Inserting elements in the search URL

I have an API call(https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${e.target.value}), what I want to do with this is to find multiple elements based on that e.target.value. I have the following setup:

import React, {useState} from 'react'
import { useGlobalContext } from './helpers/context'

export default function IngredientPage() {
  var {cocktails} = useGlobalContext()
  const {ingredients} = useGlobalContext()
  const [cocktailList, setCocktailList] = useState([])
  
  const handleSubmit = (e) => {
    console.log(e.target.value)
  }

  const handleDropdownChange = async (e) => {
    // const ingredientURL = fetch(`www.thecocktaildb.com/api/json/v1/1/filter.php?i=${e.target.value}`)
    // const selectedIngredientData = ingredientURL.json()
    // console.log(selectedIngredientData)
    const response = await fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${e.target.value}`)
    const data = await response.json()
    const {drinks} = data
    setCocktailList(drinks)
  }

  if(cocktails.length < 1) {
    return <h2 className="section-title">No cocktails available</h2>
  }
    return (
        <div>
          <div className="form-group">
          <label>Select Ingredients</label>
          <select className="form-control" onChange={handleDropdownChange}>
          {
            ingredients.map((item) => {
                return <option key={item.ingredient} value={item.ingredient}>{item.ingredient}</option>
            })
          }
          </select>
          <button onClick={handleSubmit} type="button" className="btn btn-primary">
             <i className="fas fa-search"></i>
          </button>
          </div>
          {
            cocktailList.map((cocktail) => {
              return (
                <div key={cocktail.idDrink} className="col-sm">
                  <div className="card" style={{width: "18rem",marginTop: "2rem"}}>
                  <img className="card-img-top" src={cocktail.strDrinkThumb} alt="name" />
                  <div className="card-body">
                   <h5 className="card-title">{cocktail.strDrink}</h5>
                  </div>
                  </div>
              </div>
              )
            })
          }
        </div>
    )
}

I want to find a way so I can select multiple elements or maybe when I press the button, it will add the elements in a list and implement another button for searching. Until now I can only search based on one item. Any ideas how can I do that?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It looks like that API takes a comma separated list of ingredients.

  • Search by ingredient

    www.thecocktaildb.com/api/json/v1/1/filter.php?i=Gin
    www.thecocktaildb.com/api/json/v1/1/filter.php?i=Vodka
    
  • Filter by multi-ingredient (only available to $2+ Patreon supporters)

    www.thecocktaildb.com/api/json/v1/1/filter.php?i=Dry_Vermouth,Gin,Anis
    

Assuming you've correct access, you can specify the select element to select multiple options using the multiple attribute. This will require updating the onChange handler logic to iterate the selected options. Create an array of selected options and join them with "," for the queryString value.

const handleDropdownChange = async (e) => {
  const { options } = e.target;
  const selected = [];
  for (const option of options) {
    if (option.selected) selected.push(option.value);
  }

  try {
    const response = await fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${selected.join(",")}`);
    const { drinks } = await response.json();
    setCocktailList(drinks);
  } catch(error) {
    // handle any errors
  }
}

...

<select
  multiple
  className="form-control"
  onChange={handleDropdownChange}
>
  {ingredients.map((item) => (
    <option key={item.ingredient} value={item.ingredient}>
      {item.ingredient}
    </option>
  ))}
</select>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda