I have been trying to access the API data inside my html code but I could not instead this error message keep showing.
This is the error
message: App.js:13 Uncaught TypeError: data.map is not a function
Here is the code snippet of the data fetching
export async function getUsers () {
try {
const response = await fetch('https://cornie-assessment.herokuapp.com/users/8wdkcw05bdEa47R')
return response.json()
} catch (err) {
console.log(err);
}
}
Then I imported it to my app.js file. Here is also the code
import { useEffect, useState } from 'react';
import {getUsers} from './Components/Request'
function App() {
const[data, setData] = useState([])
useEffect(() => {
getUsers().then(data => {
setData(data)
console.log(data)
})
}, [])
return (
<div className="App">
{
data.map(items => (
<article>{items.data.email}</article>
))
}
</div>
);
}
export default App;
CodePudding user response:
Please check your API response and the data which you're setting to state.
map
function work on an array.
As I have seen your API response -> It's an object type.
{"status": true, "data": [...], ...}
So, you should set the state like the below.
getUsers().then(res => {
setData(res.data) // it will be an array
console.log(res) // it's an object
})
CodePudding user response:
Your response is an object { status : true, data: [...] }. You are using an array method ( map ) on the object. Try this
getUsers().then(response => {
setData(response.data)
})
}, [])
CodePudding user response:
problem is related assigning the response data as array
export async function getUsers () {
try {
const response = await fetch('https://cornie-assessment.herokuapp.com/users/8wdkcw05bdEa47R')
const result = await response.json()
return result.data; // now you have an array of objects
} catch (err) {
console.log(err);
}