I have a js class in which I'm calling info from the startwars API. I make the response into an object array but when I assign to my State I get an error in my other component(the component is fine when I make the same info that I'm asking from the API static but when I ask from API using fetch I get an error). Here is what I have tried so far:
STATE--------
this.state = {
data:users
}
componentDidMount(){
const urls=[
'https://swapi.co/api/people/1/',
'https://swapi.co/api/people/2/',
'https://swapi.co/api/people/3/'
]
const getdata= async function(){
const people= await Promise.all(urls.map(async function(url){
const response=await fetch(url);
return response.json();
}))
---> error causing line this.setState({data:people})
console.log("people1",people);
}}
and Second way only trying one of the links---------------------
componentDidMount()
{
fetch('https://swapi.co/api/people/1')
.then(response=>response.json())
.then(users=>this.setState({data:users}));
}
If I do not use this method the rest of my code works even when I used it with it since this method waits a bit for the component to be mounted I see how the page is in the back then goes to error.
This where the data goes to and give me an error it says data1.map is not a function;
const Cardlist= ({data1})=>{
return(
<div>
{data1.map((user,i) => {
return (
<Card1
name={data1[i].name}
homeworld={data1[i].mass+ " lb"}
/>
);
})}
</div>
);
}
Also this is my render
render(){
return(
<div>
<Cardlist data1={this.state.data}/>
</div>
)
}
If anyone could just enlighten me that would be much appreciated.