I've been trying to get the Star Wars API running on my app but to no avail. So I started from scratch and created a completely empty react app solely for testing my API. I set the state as an empty array, then I fetched the api and set state equal to the json data. Console logging the api data works fine, and i'm able to see all of the objects displayed, however setting it as state breaks things. Earlier I attempted to loop through the objects but it didn't seem to work.
So far I have this
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(){
super()
this.state = {
jedi: []
}
}
componentDidMount(){
fetch('https://swapi.co/api/people/1/?format=json').then(response => {
return response.json()})
.then(data => {
// Work with JSON data here
this.setState({jedi: data });
}).catch(err => {
console.log(err)
// Do something for an error here
});
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
{this.state.jedi}
</p>
</div>
);
}
}
export default App;
This is the error:
×
Objects are not valid as a React child (found: object with keys {name, height, mass, hair_color, skin_color, eye_color, birth_year, gender, homeworld, films, species, vehicles, starships, created, edited, url}). If you meant to render a collection of children, use an array instead.
in p (at App.js:37)
in div (at App.js:32)
in App (at index.js:7)
You cannot put object like that, easiest way is to use
this.setState({jedi: JSON.stringify(data) });