Displaying JSON data using Fetch API and map() in Javascript/Reactjs
14,025
Try using
fetch(`http://api.icndb.com/jokes`)
.then(result => result.json())
.then(jokes => this.setState({jokes: jokes.value}))
instead.
This is because the response from the API is like this:
{
"type": "...",
"value": [the value you want],
}
You want the value of the value
key, because that’s what you’re using later.
Author by
Chris
Updated on June 14, 2022Comments
-
Chris almost 2 years
I have been trying to grab json data from an API and display it using the map() function. Unfortunately the API returns data in the format: { "type": ..., "value": ... }. The second object value contains an array with the data I want to access.
Is there a way I can access (or single out) JUST the second object in the API? and then I can run map() on it. See code below. This currently returns the error: this.state.jokes.map is not a function
P.S. the code works pefectly on APIs wrapped in an array e.g. http://jsonplaceholder.typicode.com/posts
class JokeList extends React.Component { constructor() { super(); this.state = {jokes:[]}; } componentDidMount() { fetch(`http://api.icndb.com/jokes`) .then(result => result.json()) .then(jokes => this.setState({jokes})) } render () { return ( <div> {this.state.jokes.map(joke => <div key={joke.id}> {joke.joke} </div>)} </div> ); } }