Home > Software design >  ReactJS API filter
ReactJS API filter

Time:08-14

I am using trying to fetch an API and am using the react state hook.

The output of the API is enter image description here

I want to get rid of all the duplicates in the base Symbol so that there should only be one baseSymbol. However, I am struggling to figure out how to do that especially if I want to use react state hooks. There's a total of 100 items in the array, so there's different types of duplicates. I'm not really sure what to do when after I filter it out, how would I re-render it.

My code for receiving the API is

const URL = "https://api.coincap.io/v2/markets/";
const [cryptoOptions, setCryptoOptions] = useState([]);
useEffect(() => {
    fetch(URL)
      .then((res) => res.json())
      .then((data) => {
        setCryptoOptions(data.data);
      });
  }, []);

CodePudding user response:

You can do it like this:

import { useState, useEffect } from "react";

const distinctBy = (arr, f) => {
  return arr.filter((a, i) => arr.findIndex((b) => f(a) === f(b)) === i);
};

export default function App() {
  const URL = "https://api.coincap.io/v2/markets/";
  const [cryptoOptions, setCryptoOptions] = useState([]);

  useEffect(() => {
    fetch(URL)
      .then((res) => res.json())
      .then((data) => {
        const filteredOptions = distinctBy(data.data, (v) => v.baseSymbol);
        setCryptoOptions(filteredOptions);
      });
  }, []);

  return cryptoOptions.map((c) => (
    <div key={c.baseSymbol}>
      {c.rank} {c.baseSymbol} {c.baseId}
    </div>
  ));
}

Working example

It is recommended to use react-query, swr or another library for data fetching.

CodePudding user response:

You can use filter() object to display items. As this javascript function allow you to filter the items according to you.

you need to first get the data in an object like-

var data = ["LTC", "BTC", "ZEC", "WAVES"]
function newData(data){
return [...new Set(data)]
console.log(newData(data))
}

the Set element of ES6 allows you to get unique values.. you can try this on your data...

But first you need to filter that particular row of data.. for that you can use filter() element of ES6.

Hope you like the answer if you found any issue just lemme know.

  • Related