I am struggling to pull through the api to the front end. I completed it successfully with https://jsonplaceholder.typicode.com/ Just mapped out the arrays. i am struggling however to pull through this seperate api I wanted to use
the erro is.. "Uncaught TypeError: Cannot read properties of undefined (reading 'results')"
so clearly it isnt actually able to get hold of results
What am I doing wrong?
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
list: []
};
}
componentDidMount() {
fetch('https://gateway.marvel.com/v1/public/comics?apikey=3cb62d086d5debdeea139095cbb07fe4&ts=redant&hash=140e85a50884cef76d614f6dacada288')
.then (response => response.json())
.then(users => this.setState({list:users}))
}
render() {
return (
<div className='App'>
{
this.state.list.data.results.map(result =>
<h1 key={result.id}>{result.urls}</h1>
)
}
</div>
)
}
}
export default App
CodePudding user response:
Here's what you can do inside your then part after fetching the results
this.setState({list:users.data.results}
And inside the map function, do the following:
this.state.list.map(result =>
<h1 key={result.id}>{result.urls}</h1>
You are getting an error because List is initially empty it doesn't have any key
called as results
, once you fetch the result only then can you loop through your result.
Another solution would be to simply add a loader, you can control that via state as well.
CodePudding user response:
The error Uncaught TypeError: Cannot read properties of undefined (reading 'results')
in your code means that this.state.list.data
returns as undefined
. This means that you'll need to focus on your state property list
to ensure that it has a data
property. As we see in your constructor, data
is initialized to an empty array which does not contain the data
property.
Something we can do to prevent the error is to surround your code with an undefined check:
if (this.state.list.data != undefined) {
this.state.list.data.results.map(result =>
<h1 key={result.id}>{result.urls}</h1>
)
}
At this point, though, we don't know if your API call is returning good data or not since your program throws the error before that (since the fetch and setState are asynchronous), so the code above mainly addresses the error that you're getting rather than focusing on the "pull through the api to the front end" portion of your question.