Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter data after data is fetched in React?

I’m new in React. I’m try to filter data after this data will received.
I have select tag with options and I want to change data array after select will changed.
For example if selected option will have value ‘crypto’ show array only with type ‘crypto’
Thanks for answer

import { useState, useEffect } from 'react'


const Fetch = () => {
    const [data, setData] = useState();
    const [currency, setCurrency] = useState('crypto');
    const [isLoaded, setIsLoaded] = useState(false);

    useEffect(() => {
        fetch('https://api.coingecko.com/api/v3/exchange_rates')
            .then((res) => { return res.json() })
            .then((res) => { setData(res.rates); setIsLoaded(true); console.log(res); })
    }, [])


    if (!isLoaded) {
        return <h2>Waiting for data...</h2>
    } else {
        return (
            <div>
                <label htmlFor="currency">Choose currency: </label>
                <select id='currency' onChange={setCurrency}>
                    <option value="all">All</option>
                    <option value="crypto">Crypto</option>
                    <option value="fiat">Fiat</option>
                    <option value="commodity">Commodity</option>
                </select>

                {Object.values(data).map((item, i) => {
                    return (
                        <div key={i}>
                            <h3>{item.name}({item.unit}) : <span style={{ color: "red" }}>{item.value}</span></h3>
                            <p>type: {item.type} </p>
                            <hr />
                        </div>
                    )
                })}

            </div>
        )
    }
}

export default Fetch;

If statement not working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To filter data in JavaScript, you may use the filter function:

Object.values(data)
      .filter(item => item?.type === currency)
      .map(...)

Pass a function of your choice that returns either true or false for each value in the array.

If you want more details, you can find them in the docs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading