'Axios with random API
I am trying to use random API in my application using axios and I get error that "TypeError: randomData.map is not a function". Maybe someone could tell me what I'm doing wrong?
import './App.css';
import {useEffect, useState} from "react";
import axios from 'axios';
function App() {
const [randomData, setRandomDate] = useState([])
useEffect(() => {
axios.get('https://randomuser.me/api')
.then(res => {
console.log('Getting from: ', res.data)
setRandomDate(res.data)
})
.catch(err => console.log(err))
}, [])
const arr = randomData.map((data, index) => {
return (
<p>{data}</p>
)
})
return (
<div className="App">
<h1>Learning React:</h1>
{arr}
</div>
);
}
export default App;
Solution 1:[1]
Your issue is that randomuser api returns an object
{
info: ...,
results: [{}]
}
so when you setRandomData to just res.data, you are assigning an object to your state, and map is not part of an object prototype.
What you need to do is to replace setRandomDate(res.data) with setRandomDate(res.data.results) and now you will be able to map that array.
like
const arr = randomData.map((data, index) => {
return (
<p>{data.email}</p>
)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dukenicols |
