Search code examples
javascriptreactjsapi-design

React - TypeError: jokes.map is not a function


I am relatively new to React and I am trying to build a simple app that queries a Chuck Norris API and returns a random joke. When I run my code in the browser I get the following error message:

TypeError: jokes.map is not a function

My theory is 'map' expects an array - which my json data object is not - however I am not positive and unsure as to what / how to tweak my code if that even is the case.

Here is my code:

This is App.js:

import React, {Component} from 'react';
import Norris from './components/norris';


class App extends Component {
 render() {
    return (
        <Norris jokes={this.state.jokes} />
    )
 }

 state = {
    jokes: []
 };

 componentDidMount() {
    fetch('https://api.chucknorris.io/jokes/random')
        .then(res => res.json())
        .then((data) => {
            this.setState({ jokes: data})
        })
        .catch(console.log)
}

}

export default App;

Here is norris.js:

import React from 'react'

const Norris = ({jokes}) => {
 return (
    <div>
        <center><h1>Norris Jokes</h1></center>
        {jokes.map((joke) => (
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{joke.value}</h5>
                </div>
            </div>
        ))}
    </div>
 )
};

export default Norris

Solution

  • The response of https://api.chucknorris.io/jokes/random is not an array

    If you want jokes as an array you can change your code like the following:

    componentDidMount() {
        fetch('https://api.chucknorris.io/jokes/random')
            .then(res => res.json())
            .then((data) => {
                this.setState({ jokes: [data]})
            })
            .catch(console.log)
    }