I have this what may seem like a simple problem for more experienced developers but it has been irritating me for quite a while.
I keep having .map is not a function, although it clearly is. see the code below
I am iterating over the results state, but it doesn't seem to work
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<App.js>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import "./App.css";
import React, { useEffect, useState } from "react";
import ContactCard from "./ContactCard";
const App = () => {
const [results, setResults] = useState([]);
useEffect(() => {
fetch("https://randomuser.me/api/?results=5")
.then((response) => response.json())
.then((data) => {
console.log(data);
setResults(data);
});
}, []);
return (
<div>
{results.map((result, i) => {
return (
<ContactCard
key={i}
avatarUrl={result.picture.large}
name={result.name}
email={result.email}
age={result.dob.age}
/>
);
})}
</div>
);
};
export default App;
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>
import React, { useState } from "react";
const ContactCard = (props) => {
const [showAge, setShowAge] = useState(false);
const showAgefn=()=>{
setShowAge(!showAge)
}
return (
<div className="contact-card">
<img src={props.avatarUrl} alt="profile" />
<div className="user-details">
<p>Name: {props.name}</p>
<p>Email: {props.email}</p>
<button onClick={showAgefn}>Show age</button>
{showAge && <p>Age: {props.age}</p>}
</div>
</div>
);
};
export default ContactCard;
CodePudding user response:
Try this
{results.results.map((result, i) => {
return (
<ContactCard
key={i}
avatarUrl={result.picture.large}
name={result.name}
email={result.email}
age={result.dob.age}
/>
);
}
i prefer to rename my state to [data, setData]
then I can use data.results instead of results.results
CodePudding user response:
This issue is that the response you are getting from https://randomuser.me/api/?results=5 is like as follows
{
"results": [...],
"info": {...}
}
So in your useEffect just modify the following
useEffect(() => {
fetch("https://randomuser.me/api/?results=5")
.then((response) => response.json())
.then((data) => {
console.log(data);
setResults(data.results); // Just modify this line
});
}, []);
All Other things are perfectly fine
CodePudding user response:
Saving the state like so [users, setUsers]
Then adding Array.from inside the curly brackets seem to have solved the issue
return (
<div>
{Array.from(users.map((user, i) => {
return (
<ContactCard
key={i}
avatarUrl={user.picture.large}
name={user.first}
email={user.email}
age={user.dob.age}
/>
);
}))}
</div>
);
CodePudding user response:
Hope it Helps
First results keyword is the state and Second results keyword is for the array. Don't Forget to use ?.map as if the map is null it won't return any error. It's a check if there is any data in map or not.
{results.results?.map((result, i) => {
return (
<ContactCard
key={i}
avatarUrl={result.picture.large}
name={result.name}
email={result.email}
age={result.dob.age}
/>
);
}