Home > Mobile >  Assign index to array, and onClick pass it based on item's position
Assign index to array, and onClick pass it based on item's position

Time:05-29

I have a searchbar that shows search suggestions from an API using .filter().includes(string).

In short: I need to dynamically assign index to array of search results - everytime it displays a different amount of results

If someone types 'b' it'll show all items starting with B. However, onClick it will only add the first at the top. Because I hard coded it this way. I need to find a way to set an index for each item of the search filter, and then pass it instead of [0] like so [i] (i = index that corresponds to the desireable search from array) to this function thats executed onClick

    const handleAdd = (e) => { // onClick={handleAdd} 
    e.preventDefault();
    setCryptolist(
      [ ... cryptolist , 
        {
      id: filteredCoins[0]['id'], // [i]
      current_price: filteredCoins[0]['current_price'], // [i]
      name: filteredCoins[0]['name'], // [i]
      symbol: filteredCoins[0]['symbol'], // [i]
      image: filteredCoins[0]['image'], // [i]
      price_change_percentage_24h: filteredCoins[0]['price_change_percentage_24h'], // [i]
      }
    ]
  )
}

As you can see, it's hard coded to add the item with index 0 from this array:

(3) [{…}, {…}, {…}]
0: {id: 'bitcoin', symbol: 'btc', name: 'Bitcoin', image: 'https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579', current_price: 28982, …}

1: {id: 'binancecoin', symbol: 'bnb', name: 'BNB', image: 'https://assets.coingecko.com/coins/images/825/large/bnb-icon2_2x.png?1644979850', current_price: 307.58, …}

2: {id: 'binance-usd', symbol: 'busd', name: 'Binance USD', image: 'https://assets.coingecko.com/coins/images/9576/large/BUSD.png?1568947766', current_price: 1.001, …}

length: 3[[Prototype]]: Array(0)

Please let me know if I explained the problem clearly, and how shoould I tackle it.

Lastly here's how I'm filtering the searches:

  const filteredCoins = coins.filter(coin =>
    coin.name.toLowerCase().includes(search.toLowerCase())
  );

I greatly appreciate any help.

  • Related