Chris
Chris

Reputation: 382

Displaying JSON data using Fetch API and map() in Javascript/Reactjs

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>
        );
    }
}

Upvotes: 2

Views: 16925

Answers (2)

IT-ACADMY
IT-ACADMY

Reputation: 1

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>
        );
    }
}

Upvotes: 0

Jed Fox
Jed Fox

Reputation: 3025

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.

Upvotes: 8

Related Questions