Tengo una variedad de monedas que me gustaría mapear. Pero no estoy seguro de cómo? Mi aplicación falla con el código que escribí y devuelve una página vacía con un error: currencyList.map is not a function
Esto es lo que obtengo cuando consola. registro los datos obtenidos:
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'}
Hay muchas más entradas allí..
de todos modos este es mi código
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> )
Por lo que entiendo, tienes un objeto, no una matriz como respuesta, algo así como:
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'} }
Así que no hay mapa en los objetos. Necesitará obtener las claves, por ejemplo:
Object.keys(currencyList).map( key => <div>{currencyList[key].id}</div> )
Si desea obtener los valores,
Object.values(currencyList) // You can save Object.values(res?.data?.results || {}) into the currencyList too, // eg setCurrencyList(Object.values(res?.data?.results || {})
luego se convertirá en una matriz con todos los objetos de valores. Si desea mapearlo y pasar a un componente,
Object.values(currencyList).map(currency => <Component item={currency} key={currency.id} />)