简体   繁体   中英

Fetch data then save it to state in ReactJS

I have a react application where I'm fetching data from coingecko API. I was able to display all the data using .map and I was able to filter the cryptocurrencies based on what user types into the searchbar. With this:

function FetchCrypto() {
  const [coins, setCoins] = useState([]);
  const [search, setSearch] = useState('');

  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);
        console.log(res.data);
      })
      .catch(error => console.log(error));
  }, []); // this basically just fetches the data and stores it in Coins state

  const handleChange = e => {
    setSearch(e.target.value);
  }; // update search state to filter for coins (based on what user typed into searchbar)

  const filteredCoins = coins.filter(coin =>
    coin.name.toLowerCase().includes(search.toLowerCase())
  ); // this is to filter the array of data, and display "bitcoin" if user types in "bitcoin" instead of displaying the entire database

  return (
    <div className='coin-app'>
      <div className='coin-search'>
        <h1 className='coin-text'>Search a currency</h1>
        <br></br>
        <form>
          <input
            className='coin-input'
            type='text'
            onChange={handleChange}
            placeholder='Search'
          />
        </form>
      </div>
      {filteredCoins.map(coin => {
        return (
          <Coin
            key={coin.id}
            name={coin.name}
            price={coin.current_price}
            symbol={coin.symbol}
            image={coin.image}
            priceChange={coin.price_change_percentage_24h}
          />
        );
      })}
    </div>
  );
}

export default FetchCrypto;

However, instead of mapping through the entire database and displaying it. I want to give users the ability to pick a few entries ( cryptos ) and save it so they don't have to go thru everything to see what they're interested in.

I was thinking to .push() the data from filteredCoins into an array and then use LocalStorage to persist state. Not really sure how to handle this.

here's how it looks like so far after being mapped ( the refresh and delete buttons in the corner of each entry don't work yet.. but I'd like to add a + button to give it the functionality I just spoke about )

加密网站实践

当按下 add do localStorage.setItem("name",value) 然后你可以通过 localStorage.getItem("name") 访问它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM