Mateusz Szumilo
Mateusz Szumilo

Reputation: 57

How to map an array of objects in react?

I have an array of currencies that I'd like to map out. But I'm not sure how? My app crashes with the code I wrote and returns an empty page with an error: currencyList.map is not a function

This is what I get when I console.log the fetched data:

AED: {currencyName: 'UAE Dirham', id: 'AED'}
AFN: {currencyName: 'Afghan Afghani', currencySymbol: '؋', id: 'AFN'}
ALL: {currencyName: 'Albanian Lek', currencySymbol: 'Lek', id: 'ALL'}
AMD: {currencyName: 'Armenian Dram', id: 'AMD'}
ANG: {currencyName: 'Netherlands Antillean Gulden', currencySymbol: 'ƒ', id: 'ANG'}
AOA: {currencyName: 'Angolan Kwanza', id: 'AOA'}

There are lots more entries there..

anyways this is my code

const [currencyList, setCurrencyList] = useState<any>();

  useEffect(() => {
    axios.get(listOfCurrencies)
    .then(res => {
      setCurrencyList(res.data['results']);
      console.log(res.data['results'])
    })
    .catch(error => {
      console.log("there was an error with connecting to database")
    })

  }, []);

return (
      <div>
        <h1> data will be here </h1>
          {currencyList && currencyList.map(curr => {
            return(
              <div>
                {curr}
              </div>
            )

          })}
      </div>
)

Upvotes: 0

Views: 876

Answers (2)

CY Lim
CY Lim

Reputation: 126

If you want to get the values,

Object.values(currencyList) 
// You can save Object.values(res?.data?.results || {}) into the currencyList too, 
// e.g. setCurrencyList(Object.values(res?.data?.results || {})

then it will become an array with all the values object. If you want to map it and pass into a component,

Object.values(currencyList).map(currency => <Component item={currency} key={currency.id} />)

Upvotes: 1

Alfonso Tienda
Alfonso Tienda

Reputation: 3689

For what I understand, you have an object, not an array as response, kind of:

const currencyList = {
  AED: {currencyName: 'UAE Dirham', id: 'AED'}
  AFN: {currencyName: 'Afghan Afghani', currencySymbol: '؋', id: 'AFN'}
  ALL: {currencyName: 'Albanian Lek', currencySymbol: 'Lek', id: 'ALL'}
  AMD: {currencyName: 'Armenian Dram', id: 'AMD'}
  ANG: {currencyName: 'Netherlands Antillean Gulden', currencySymbol: 'ƒ', id: 'ANG'}
  AOA: {currencyName: 'Angolan Kwanza', id: 'AOA'}
}

So there's no map in objects. You'll need to get the keys, for example:

Object.keys(currencyList).map(
 key => <div>{currencyList[key].id}</div>
)

Upvotes: 1

Related Questions