I'm trying to render the fetched data on my page but I can only see the data through console.log and keep getting this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
// import StudentContainer from './containers/StudentContainer';
const API = 'https://api.hatchways.io/assessment/students';
class App extends Component {
constructor(props) {
super(props)
this.state = {
allStudents: []
}
}
componentDidMount() {
fetch(API)
.then(resp => resp.json())
.then(students => {
console.log(students.students[0].city)
this.setState({
allStudents: students.students
})
});
}
// <StudentContainer allStudents={allStudents} />
render () {
console.log("state:",this.state)
const { allStudents} = this.state
return (
<div className="App">
{console.log("students:", allStudents[0])}
<h2>Students: {allStudents[0]} </h2>
</div>
)
}
}
export default App;
this console.logs an object with key values in it
{console.log("students:", allStudents[0])}
but right on the bottom when I try to render it on the page,
<h2>Students: {allStudents[0].city} </h2>
it becomes undefined.
Here's a snippet of the data:
{city: 'Fushë-Muhurr', company: 'Yadel', email: '[email protected]', firstName: 'Ingaberg', grades: Array(8), …}
city: "Fushë-Muhurr"
company: "Yadel"
email: "[email protected]"
firstName: "Ingaberg"
grades: (8) ['78', '100', '92', '86', '89', '88', '91', '87']
id: "1"
lastName: "Orton"
pic: "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg"
skill: "Oracle"```
CodePudding user response:
The rule is you CANNOT display raw object onto the UI/HTML. Either create actual component/HTML using the object's data, or just JSON.stringify
them.
In your App, try changing the line with the <h2>
tag into: <h2>Students: {JSON.stringify(allStudents[0])} </h2>
Another problem is in this line of your StudentContainer
component <> {"studentcontainer:", props.allStudents.map(student => student.city)}</>
.
A string, then a comma, then an array is not really valid JS. Try changing this to <pre>{JSON.stringify(props.allStudents.map(student => student.city))}</pre<
and it should display at least.
(This portion is strikethroughed because OP removed the code on the StudentContainer
component to simplify his question, which is great)
CodePudding user response:
{allStudents.map((item, i) => (
<div key={i} className="App">
<h2>Students: {item.city} </h2>
</div>
))}
Try this , i tested it for you and it works .