2

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.