Home > Mobile >  Sorting data from an API (redux-toolkit)
Sorting data from an API (redux-toolkit)

Time:03-25

I'm building a crypto app with react and redux-toolkit. I'm trying to find a way to manage the data from the API. More specifically i want to be able to sort by value, volume, etc. and add an "isFavourite" property for each coin but i think (correct me if i'm wrong) that the only way to do this is by copying the data to another state. What i've tried so far was adding another state where i passed the data like this:

const [list, setList] = useState()
    useEffect(() => {
        setList(data)
    }, [data])


//"const coinData = list?.data?.coins" instead of "const coinData = data?.data?.coins"

but then an error occured because the data on the "list" were "undefined". The code bellow is the one that is running without any problems. How can i manage the API data? Am i on the right path or is there a more slick way to do what i want? Thank you!

function Main () {
    const { data, error, isFetching } = useGetCryptosQuery()

    if(isFetching) return 'Loading...'

    const globalStats = data?.data?.stats
    const coinData = data?.data?.coins
  
    const coinList = coinData.map(coin => {
        return (
        <Coin 
            price = {coin.price}
            key = {coin.uuid}
            id = {coin.uuid}
            name = {coin.name}
            icon = {coin.iconUrl}

        />)
    })

    
    return (
        <div>
            <h2>Main</h2>
           
               {coinList}

        </div>

    )
}

export default Main

CodePudding user response:

You are on the right track - I set up something similar and added a check for null trying to map the data, and that avoids the error you probably got.

const coinList = coinData ? coinData.map((coin) => {
///...coin component 
}) : <div></div>;

Then, instead of an error for undefined data, it will return an empty div - until the data is there, then it will render ok.

  • Related