import React, {useState, useEffect} from "react";
import './App.css';
function App() {
const [ data, setData ] = useState([]);
useEffect( ()=> {
loadData();
//getData();
}, []);
const loadData = async () => {
await fetch("https://randomuser.me/api")
.then(response => response.json())
.then(receiveddata => setData(receiveddata));
}
console.log(data);
return (
<div className="App">
<p> Fetch/ Async/ Await</p>
{data.map(user => (
<div key={user.id}>{user.name}, {user.email}</div>
))}
</div>
);
}
export default App;
I'm getting this error on the console,
Uncaught TypeError: data.map is not a function
You are getting the error because data is not an Array. The response that you are getting back is an object that has two properties results and info. Since your state is an array, set the state to receiveddata.results instead.
Firsteval, your console.log(data) will return nothing, because the state will not be updated when your code will run the console.log() ; so don't expect to get debug info with that.
Next, your response is an object, not an array.
You can do this way : setData(receiveddata.results) then you can map() your data.
In your render you should also check if map is not empty like this:
{data && data.map(user => (
<div key={user.id}>{user.name}, {user.email}</div>
))}
You need to check the structure of data comping from your API. Your array is inside "results" property. And "title" is an object as well. You can find a working example of your code over here CodeSandbox. Check the console you will better understand the structure of your response