Reputation: 91
I'm working on a simple React web app and I'm having problem viewing certain data I'm pulling from this mock api: https://randomuser.me/api/
Here is my code:
import React, { Component } from 'react';
class ApiTest extends Component {
constructor() {
super();
this.state = {
names: [],
};
}
componentDidMount() {
fetch('https://randomuser.me/api/?results=10')
.then(results => {
return results.json();
}).then(data => {
let names = data.results.map((name) => {
return(
<div key={name.results}>
{name.title}
</div>
)
})
this.setState({names: names});
console.log("state", this.state.names);
})
}
render() {
return (
<div className="App">
<div className="container2">
<div className="container1">
{this.state.names}
</div>
</div>
</div>
);
}
}
export default ApiTest;
I am able to pull in the pictures based off the tutorial I found for all of this (https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2) but I can't seem to get anything else to display. I don't seem to be getting any errors and I see these objects in the console. What am I doing wrong here? Thanks guys!!!
Upvotes: 2
Views: 520
Reputation: 2721
it's really not a very good idea to put jsx into your component state. State should consist of plain data. Then you can transform you data in a flexible manner inside render()
function:
https://codesandbox.io/s/qqy9l78l06
import React, { Component } from "react";
class ApiTest extends Component {
constructor() {
super();
this.state = {
people: []
};
}
componentDidMount() {
fetch("https://randomuser.me/api/?results=10")
.then(results => results.json())
.then(data => this.setState({ people: data.results }));
}
render() {
console.log(this.state);
return (
<div className="App">
<div className="container2">
<div className="container1">
{this.state.people.map(person => (
<div>{person.name.first}</div>
))}
</div>
</div>
</div>
);
}
}
export default ApiTest;
Upvotes: 1