'Fetch ONLY certain data from API and store it in State or a variable in REACT/JS

I'm trying to destructure data from an API - because I want to be able to keep some specific information and ignore the rest. So far, I was able to map everything

function FetchCrypto() {
  const [coins, setCoins] = useState([]); // api data stored here

  useEffect(() => {
    axios
      .get(
        'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false'
      ).then(res => {
        setCoins(res.data);
      }).catch(error => console.log(error));
  }, []); // API CALL

and even filter the API to get specific data

  const [search, setSearch] = useState(''); // keyword from searchbar to find an item by name

  const handleChange = e => {
    setSearch(e.target.value);
  }; // state for keyword from searchbar

  const filteredCoins = coins.filter(coin =>
    coin.name.toLowerCase().includes(search.toLowerCase())
  ); // filetr data to get only 1 item from array

Now, I'm trying to destructure the previously filtered data, so I can store it in a variable and then save it to localStore (so that I don't have to continuously keep searching for it, because there will be multiple things that I want to keep track of)


  const [cryptolist, setCryptolist] = useState([{
    id: '',
    price: '',
    name: '',
    symbol: '',
    image: '',
    percentChange: '',
  }]) // 

  const handleAdd = (e) => {
    e.preventDefault();
    const { 0: { id, symbol, current_price, name, image, price_change_percentage_24h } } = filteredCoins;

   console.log(id, symbol, current_price, name, image, price_change_percentage_24h);
  } // here I destructured the item, but I don't know how to setCryptolist state using it

Here's how the object looks like when filtered:

0: //
ath: 69045
ath_change_percentage: -57.38798
ath_date: "2021-11-10T14:24:11.849Z"
atl: 67.81
atl_change_percentage: 43288.5943
atl_date: "2013-07-06T00:00:00.000Z"
circulating_supply: 19046287
current_price: 29432
fully_diluted_valuation: 617848810037
high_24h: 29626
id: "bitcoin"
image: "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579"
last_updated: "2022-05-22T06:03:33.555Z"
low_24h: 29229
market_cap: 560367893265
market_cap_change_24h: 2526851671
market_cap_change_percentage_24h: 0.45297
market_cap_rank: 1
max_supply: 21000000
name: "Bitcoin"
price_change_24h: 122.38
price_change_percentage_24h: 0.41753
roi: null
symbol: "btc"
total_supply: 21000000
total_volume: 12815210836
[[Prototype]]: Object

and unfiltered (there will be way more than just 10 entries, but for now I wanted to keep it short)

0: {id: 'bitcoin', symbol: 'btc', name: 'Bitcoin', image: 'https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579', current_price: 29432, …}
1: {id: 'ethereum', symbol: 'eth', name: 'Ethereum', image: 'https://assets.coingecko.com/coins/images/279/large/ethereum.png?1595348880', current_price: 1973.71, …}
2: {id: 'tether', symbol: 'usdt', name: 'Tether', image: 'https://assets.coingecko.com/coins/images/325/large/Tether-logo.png?1598003707', current_price: 1.001, …}
3: {id: 'usd-coin', symbol: 'usdc', name: 'USD Coin', image: 'https://assets.coingecko.com/coins/images/6319/large/USD_Coin_icon.png?1547042389', current_price: 1.003, …}
4: {id: 'binancecoin', symbol: 'bnb', name: 'BNB', image: 'https://assets.coingecko.com/coins/images/825/large/bnb-icon2_2x.png?1644979850', current_price: 314.73, …}
5: {id: 'ripple', symbol: 'xrp', name: 'XRP', image: 'https://assets.coingecko.com/coins/images/44/large/xrp-symbol-white-128.png?1605778731', current_price: 0.411977, …}
6: {id: 'binance-usd', symbol: 'busd', name: 'Binance USD', image: 'https://assets.coingecko.com/coins/images/9576/large/BUSD.png?1568947766', current_price: 1.003, …}
7: {id: 'cardano', symbol: 'ada', name: 'Cardano', image: 'https://assets.coingecko.com/coins/images/975/large/cardano.png?1547034860', current_price: 0.526227, …}
8: {id: 'solana', symbol: 'sol', name: 'Solana', image: 'https://assets.coingecko.com/coins/images/4128/large/solana.png?1640133422', current_price: 50.08, …}
9: {id: 'polkadot', symbol: 'dot', name: 'Polkadot', image: 'https://assets.coingecko.com/coins/images/12171/large/polkadot.png?1639712644', current_price: 10.07, …}
length: 10
[[Prototype]]: Array(0)

enter image description here

Unfortunately, I'm pretty aware that I can run into problems with this approach because 0: { id, symbol, current_price, name, image, price_change_percentage_24h }

if there are two similarly named entries, then the 0 index could be given to the wrong thing..

I want to use onClick={handleAddCryptoToList} eventually, with a button to save the data.

As you have probably already guessed, it's a cryptocurrency app. Basically, I want to make "watchlist" functionality with this.. so that it's not necessary to go through the whole API, but to be able to pick certain cryptocurrencies to watch.

How should I handle this, and how can I store destructured data into a variable? Should I use a different technique? I plan to use localStorage or other way of persisting state (once, I can save such data into a variable/state).



Solution 1:[1]

Okay, I figured it out - it was so simple and yet it took me forever to get it.

If anyone is interested, here's the code that did the trick:

  const handleAdd = (e) => {
    e.preventDefault();
    setCryptolist([{
      id: filteredCoins.id,
      price: filteredCoins.current_price,
      name: filteredCoins.name,
      symbol: filteredCoins.symbol,
      image: filteredCoins.image,
      percentChange: filteredCoins.price_change_percentage_24h,
    }])
    console.log(cryptolist) 
  }

Thank you to everyone who took their time to help me figure this out. Your effort is helping the world move forward in these tough times.

EDIT:

  const handleAdd = (e) => {
    e.preventDefault();
    if (filteredCoins[0]['id'] === search) {

    setCryptolist([{
      id: filteredCoins[0]['id'],
      price: filteredCoins[0]['current_price'],
      name: filteredCoins[0]['name'],
      symbol: filteredCoins[0]['symbol'],
      image: filteredCoins[0]['image'],
      percentChange: filteredCoins[0]['price_change_percentage_24h'],
    }]);
    console.log(cryptolist) // returns undefined
  } else {
    return console.log('fetching data, please wait')
  }
  }

OKAY ! This solution seems to do the trick! I will keep testing and see if it really does work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1